C # related to incorrect user input

You have a simple console application in which the user is prompted to enter several values. The input is read through console.readline (). Ex

Name: Fred  //string
Lastname: Ashcloud //string
Age: 28 //int

I would like to make sure that int and double types are entered, and if the user enters the garbage, allows him to repeat the procedure.

For example, if a user enters “28 years old,” where age expects the application to crash. What is the best way to test these inputs?

Now I can only think:

while (!Int32.TryParse(text, out number))
{
    Console.WriteLine("Error write only numbers");
    text = Console.ReadLine();
}

Is there any other way to do this? try to catch statements if you want to give more detailed feedback to the user? How in this case?

+3
source share
4 answers

.

, .

, - .

+2
using System.Text.RegularExpressions;

int GetNumberFromString( string str_age )
{
     Regex number = new Regex("[0-9][0-9]?");
     Match n = number.Match(str_age);
     if (n.Value != "")
         return System.Convert.ToInt16(n.Value, 10);
     else
         return -1;            
}

, -1, . 0-99.

+1

Regular expressions are good.

Regex age = new Regex(@"^[0-9]*$");
while (!age.match(age_from_console)) {
    Console.WriteLine("Age Invalid, try again ->");
}
+1
source

Actually, your code is good. I would add a negative number check and possibly a huge quantity check.

+1
source

Source: https://habr.com/ru/post/1742673/


All Articles