-2

So i nearly have 2k lines of code and i have forgotten to / i do not know how to have input valdation on user inputs such as

cw("Hello Please Enter your age");
                cw("If you are in a Group Input the Age of the Youngest Member of the Group.");
                Age = Convert.ToInt32(Console.ReadLine());

I want to Make it so that users can enter only numbers and my program will not crash when they put in somthing els.

this is a common problem in the whole of my program for the console.readlines.

Is there a way on mass that i can introduce the input valdation for numbers only and letters only when approate?

thank you in advance.

3
  • You can use int.TryParse to solve your issue. Commented Dec 27, 2018 at 22:54
  • Yes (though it's been years (/decades) since I wrote a straight-up console program). Write a simple little function that takes prompts and help string, and returns a bool (true = success, false = user decided to quit). In that routine, output the prompt string and read the user's response. He can "Q"uit, ask for "H"elp or enter an appropriate value (in this case, an int). Then check for "Q" or "H". If neither, use int.TryParse and loop back on failure. Commented Dec 27, 2018 at 22:54
  • Oh, come on, I'm sure that this is a dup, but you are pointing to a question without an accepted answer. The first one that I see tests for a number with a Regex. If you scroll down about 6 answers you find the one with 5 votes that uses TryParse (the last answer I see (with 12 votes) also references TryParse). There's got to be a better one to point to that that!!! Commented Dec 27, 2018 at 23:15

1 Answer 1

0

This is what I'd do (after a little more polish):

 public static bool PromptForInt(string promptString, out int result, string helpString = null)
 {
     while (true)
     {
         Console.WriteLine(promptString);
         var response = Console.ReadLine();
         if (string.Equals(response, "Q", StringComparison.OrdinalIgnoreCase))
         {
             result = 0;
             return false;
         }

         if (helpString != null && string.Equals(response, "H", StringComparison.InvariantCultureIgnoreCase))
         {
             Console.WriteLine(helpString);
             continue;   //skip back to the top of the loop
         }

         if (int.TryParse(response, out result))
         {
             return true;
         }
     }
 }

You could right similar functions for other types (for example, double or DateTime, always using typeName.TryParse. In terms of polishing, you might want to have a useful error message if the user doesn't enter "Q", "H" or a valid int. Otherwise...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.