Reading an integer from user input

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

提交回复
热议问题