0

About an undesired type of user input

Let's say I wanted the user to enter an integer but instead they entered a string value. How can I fix it? ----- Console.WriteLine("Which day is it today in number?"); var day = Convert.ToInt32(Console.ReadLine()); ----- I tried to add a conditional to fix it like.. if (day != int) Console.WriteLine("You can only enter a number!"); but it creates an error because it says I can't write "int" there.. So what can I do?

5th Aug 2019, 2:02 AM
Aykut AKSAKAL
Aykut AKSAKAL - avatar
2 odpowiedzi
+ 2
your if statement would be irrelevant, because an error would occur prior to even reaching that statement if the compiler tried to convert say “hi” to an integer. Typically I would suggest using a regex to compare whether or not the string entered contains only digits and handling the true/false return accordingly, but I do not know how to use regex matching in C#, so perhaps instead you could wrap the code in a try/catch block? try { Console.WriteLine("Which day is it today in number?"); var day = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(day); } catch { Console.WriteLine("You can only enter a number!"); }
5th Aug 2019, 3:32 AM
Jake
Jake - avatar
0
Thanks a lot really! It works quite well thanks to your help :) As a beginner now I need to learn more about try/catch blocks
5th Aug 2019, 1:19 PM
Aykut AKSAKAL
Aykut AKSAKAL - avatar