Programing

사용자 입력에서 정수 읽기

lottogame 2020. 11. 10. 07:41
반응형

사용자 입력에서 정수 읽기


내가 찾고있는 것은 명령 줄 (콘솔 프로젝트)에서 사용자가 제공 한 정수를 읽는 방법입니다. 저는 주로 C ++를 알고 있으며 C # 경로를 시작했습니다. 나는 Console.ReadLine (); 문자 / 문자열 만받습니다. 요컨대 이것의 정수 버전을 찾고 있습니다.

내가 정확히 무엇을하는지에 대한 아이디어를 제공하기 위해 :

Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.

나는 이것을 위해 꽤 오랫동안 찾고 있었다. C에서 많은 것을 찾았지만 C #은 아닙니다. 그러나 다른 사이트에서 char에서 int로 변환하도록 제안한 스레드를 찾았습니다. 전환하는 것보다 더 직접적인 방법이 있어야한다고 확신합니다.


Convert.ToInt32 () 함수를 사용하여 문자열을 정수로 변환 할 수 있습니다.

int intTemp = Convert.ToInt32(Console.ReadLine());

다음을 사용하는 것이 좋습니다 TryParse.

Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);

이렇게하면 누군가 잘못된 입력을했기 때문에 "1q"또는 "23e"와 같은 것을 구문 분석하려고해도 응용 프로그램에서 예외가 발생하지 않습니다.

Int32.TryParse부울 값을 반환하므로 if명령문 에서이를 사용 하여 코드 분기가 필요한지 여부를 확인할 수 있습니다.

int number;
if(!Int32.TryParse(input, out number))
{
   //no, not able to parse, repeat, throw exception, use fallback value?
}

귀하의 질문에 : ReadLine()전체 명령 줄을 읽고 threfor가 문자열을 반환 하기 때문에 정수를 읽는 해결책을 찾지 못할 것 입니다. 할 수있는 일은이 입력을 int16 / 32 / 64 변수로 변환하는 것입니다.

이를위한 몇 가지 방법이 있습니다.

변환 할 입력이 확실하지 않은 경우 문자열, int 변수 또는 그렇지 않은 항목을 구문 분석하든 관계없이 항상 TryParse 메서드를 사용하십시오.

C # 7.0에서 업데이트 출력 변수는 인수로 전달되는 위치에서 직접 선언 할 수 있으므로 위의 코드를 다음과 같이 압축 할 수 있습니다.

if(Int32.TryParse(input, out int number))
{
   /* Yes input could be parsed and we can now use number in this code block 
      scope */
}
else 
{
   /* No, input could not be parsed to an integer */
}

완전한 예는 다음과 같습니다.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var foo = Console.ReadLine();
        if (int.TryParse(foo, out int number1)) {
            Console.WriteLine($"{number1} is a number");
        }
        else
        {
            Console.WriteLine($"{foo} is not a number");
        }
        Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
        Console.ReadLine();
    }
}

여기 number1에서 입력이 숫자가 아니고 값이 0 인 경우에도 변수 가 초기화 되는 것을 볼 수 있으므로 선언 if 블록 외부에서도 유효합니다.


입력을 타입 캐스트해야합니다. 다음을 사용해보십시오

int input = Convert.ToInt32(Console.ReadLine()); 

값이 숫자가 아니면 예외가 발생합니다.

편집하다

위의 내용이 빠른 것임을 이해합니다. 내 답변을 개선하고 싶습니다.

String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
      switch(selectedOption) 
      {
           case 1:
                 //your code here.
                 break;
           case 2:
                //another one.
                break;
           //. and so on, default..
      }

} 
else
{
     //print error indicating non-numeric input is unsupported or something more meaningful.
}

int op = 0;
string in = string.Empty;
do
{
    Console.WriteLine("enter choice");
    in = Console.ReadLine();
} while (!int.TryParse(in, out op));

나는 사용 int intTemp = Convert.ToInt32(Console.ReadLine());했고 잘 작동했습니다. 여기 내 예가 있습니다.

        int balance = 10000;
        int retrieve = 0;
        Console.Write("Hello, write the amount you want to retrieve: ");
        retrieve = Convert.ToInt32(Console.ReadLine());

더 나은 방법은 TryParse를 사용하는 것입니다.

Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}

I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to

  1. validate the input
  2. display an error message if invalid input is given, and
  3. loop through until a valid input is given.

This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.

static void Main(string[] args)
    {
        int intUserInput = 0;
        bool validUserInput = false;

        while (validUserInput == false)
        {
            try
            { Console.Write("Please enter an integer value greater than or equal to 1: ");
              intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
            }  
            catch (Exception) { } //catch exception for invalid input.

            if (intUserInput >= 1) //check to see that the user entered int >= 1
              { validUserInput = true; }
            else { Console.WriteLine("Invalid input. "); }

        }//end while

        Console.WriteLine("You entered " + intUserInput);
        Console.WriteLine("Press any key to exit ");
        Console.ReadKey();
    }//end main

In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to

if ( (intUserInput >= 1) && (intUserInput <= 4) )

This would work if you needed the user to pick an option of 1, 2, 3, or 4.


Use this simple line:

int x = int.Parse(Console.ReadLine());

static void Main(string[] args)
    {
        Console.WriteLine("Please enter a number from 1 to 10");
        int counter = Convert.ToInt32(Console.ReadLine());
        //Here is your variable
        Console.WriteLine("The numbers start from");
        do
        {
            counter++;
            Console.Write(counter + ", ");

        } while (counter < 100);

        Console.ReadKey();

    }

You could just go ahead and try :

    Console.WriteLine("1. Add account.");
    Console.WriteLine("Enter choice: ");
    int choice=int.Parse(Console.ReadLine());

That should work for the case statement.

It works with the switch statement and doesn't throw an exception.


--int i = Convert.ToInt32(Console.Read());

i had to try this after reading above conversation but i found even if i pass "1" as input, it was being displayed as 49, mean to say ReadLine is the only method that can fetch exact input from user as my experience, correct my knowledge please.

참고URL : https://stackoverflow.com/questions/24443827/reading-an-integer-from-user-input

반응형