How can I check console input as integers?

I wrote my codes, and I want to check it in such a way that it allows you to enter intergers, not alphabets. Here is the code, please, I will love you to help me. Thanks.

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace minimum { class Program { static void Main(string[] args) { int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); int c = Convert.ToInt32(Console.ReadLine()); if (a < b) { if (a < c) { Console.WriteLine(a + "is the minimum number"); } } if (b < a) { if (b < c) { Console.WriteLine(b + "is the minimum number"); } } if (c < a) { if (c < b) { Console.WriteLine(c + "is the minimum number"); } } Console.ReadLine(); } } } 
+6
c # validation console
source share
9 answers

You should check if this is an int instead of converting immediately. Try something like:

 string line = Console.ReadLine(); int value; if (int.TryParse(line, out value)) { // this is an int // do you minimum number check here } else { // this is not an int } 
+12
source share

Just call Readline () and loop with Int.TryParse until the user enters a valid number :)

 int X; String Result = Console.ReadLine(); while(!Int32.TryParse(Result, out X)) { Console.WriteLine("Not a valid number, try again."); Result = Console.ReadLine(); } 

Hope that helps

+8
source share

In order for the console to filter out alphanumeric keystrokes, you must take care of the input. The Console.ReadKey () method is fundamental for this; it allows you to sniff the key pressed. Here is an example implementation:

  static string ReadNumber() { var buf = new StringBuilder(); for (; ; ) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter && buf.Length > 0) { return buf.ToString() ; } else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) { buf.Remove(buf.Length-1, 1); Console.Write("\b \b"); } else if ("0123456789.-".Contains(key.KeyChar)) { buf.Append(key.KeyChar); Console.Write(key.KeyChar); } else { Console.Beep(); } } } 

You can add, say, Decimal.TryParse () to an if () statement that detects the Enter key to verify that the string you entered is still a real number. Thus, you can reject input of type "1-2".

+7
source share

Do not convert user input immediately. Put it in a string and use Int32.TryParse (...) to find out if the number has been entered. Like this:

 int i; string input = Console.ReadLine(); if(Int32.TryParse(input, out i)) { // it is a number and it is stored in i } else { // it is not a number } 
+1
source share

note that

 if (a < b) { if (a < c) { 

equivalently

 if (a < b && a < c) { 

and that this last form introduces less nesting and is more readable, especially if your code becomes more complex. Also, you should probably never use Convert.ToInt32 - it has a particularly poorly thought out and unexpected corner case; and it is also less type safe than int.Parse , which is the best choice where possible, or int.TryParse when you're not sure if the string is correct. Basically, avoid Convert.... where possible.

+1
source share
  string Temp; int tempInt,a; bool result=false; while ( result == false ) { Console.Write ("\n Enter A Number : "); Temp = Console.ReadLine (); result = int.TryParse (Temp, out tempInt); if ( result == false ) { Console.Write ("\n Please Enter Numbers Only."); } else { a=tempInt; break; } } 
+1
source share

My preferred solution:

 static void Main() { Console.WriteLine( ( from line in Generate(()=>Console.ReadLine()).Take(3) let val = ParseAsInt(line) where val.HasValue select val.Value ).Min() ); } static IEnumerable<T> Generate<T>(Func<T> generator) { while(true) yield return generator(); } static int? ParseAsInt(string str) { int retval; return int.TryParse(str,out retval) ? retval : default(int?); } 

Of course, depending on the specification (should you try again with an invalid number?), You may need to change it.

0
source share

Double / Float:

I am simply expanding @ Hans Passant's answer (taking care of DecimalSeparator and "-"):

  static double ReadNumber() { var buf = new StringBuilder(); for (; ; ) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter && buf.Length > 0) { Console.WriteLine(); return Convert.ToDouble(buf.ToString()); } else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) { buf.Remove(buf.Length - 1, 1); Console.Write("\b \b"); } else if (System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.Contains(key.KeyChar) && buf.ToString().IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) == -1) { buf.Append(key.KeyChar); Console.Write(key.KeyChar); } else if ("-".Contains(key.KeyChar) && buf.ToString().IndexOf("-") == -1 && buf.ToString() == "") { buf.Append(key.KeyChar); Console.Write(key.KeyChar); } else if ("0123456789".Contains(key.KeyChar)) { buf.Append(key.KeyChar); Console.Write(key.KeyChar); } else { Console.Beep(); } } } 
0
source share

Try this simple

 try { string x= "aaa"; Convert.ToInt16(x); //if success is integer not go to catch } catch { //if not integer return; } 
-one
source share

All Articles