Reading an integer from user input

后端 未结 11 748
时光取名叫无心
时光取名叫无心 2020-11-22 09:44

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I

相关标签:
11条回答
  • 2020-11-22 09:51

    Try this it will not throw exception and user can try again:

            Console.WriteLine("1. Add account.");
            Console.WriteLine("Enter choice: ");
            int choice = 0;
            while (!Int32.TryParse(Console.ReadLine(), out choice))
            {
                Console.WriteLine("Wrong input! Enter choice number again:");
            }
    
    0 讨论(0)
  • 2020-11-22 09:51

    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.

    0 讨论(0)
  • 2020-11-22 09:52

    I used int intTemp = Convert.ToInt32(Console.ReadLine()); and it worked well, here's my example:

            int balance = 10000;
            int retrieve = 0;
            Console.Write("Hello, write the amount you want to retrieve: ");
            retrieve = Convert.ToInt32(Console.ReadLine());
    
    0 讨论(0)
  • 2020-11-22 09:53

    You need to typecast the input. try using the following

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

    It will throw exception if the value is non-numeric.

    Edit

    I understand that the above is a quick one. I would like to improve my answer:

    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.
    }
    
    0 讨论(0)
  • 2020-11-22 09:54

    You can convert the string to integer using Convert.ToInt32() function

    int intTemp = Convert.ToInt32(Console.ReadLine());
    
    0 讨论(0)
  • 2020-11-22 10:00

    Better way is to use TryParse:

    Int32 _userInput;
    if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
    
    0 讨论(0)
提交回复
热议问题