Reading an integer from user input

后端 未结 11 992
时光取名叫无心
时光取名叫无心 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 10:11

    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.

提交回复
热议问题