tags:

views:

60

answers:

4

Have a simple console app where user is asked for several values to input. Input is read via 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 garbage, lets him repeat the procedure.

Example, if the user enters "28 years old" where age expects int the app will crash. What is the best way to check for these inputs?

Right now I can only think of:

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

Is there any other way to do this? try catch statements if one wants to give a more detailed feedback to the user? How in that case?

+1  A: 

For a console application, your code is perfectly fine.

However, you might want to abstract that into a reusable function so that you can read different numbers without repeating the code.

Also, you might want to provide some way for the user to cancel.

SLaks
Just curious, if I decide to make a gui later on, would there be a better way to do this, or are there going to be some extra things one needs to be aware of? Thanks.
Milan
GUIs are _completely_ different, and can use built-in validation features.
SLaks
Do you have a link or some "search term" that I could use in order to read more about the gui's build-in validation features for future use? Thanks
Milan
[winforms validation](http://www.google.com/search?q=winforms+validation)
SLaks
A: 
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;            
}

This will parse any data out besides the age or return -1 if no age is present. this also assumes age 0-99.

corn3lius
A: 

Regular Expressions are good.

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

Actually, your code is good. I would add negative number check, and perhaps huge number check too.

Daniel Dolz