+ 1

How to check that the input of a user is not a letter in c sharp.

Like for example with a while loop or if function? Like if(bushels!= towhat?) { Console.Writeline(“Error, You should type an integer”) } Thanks

10th Jan 2019, 8:23 PM
Sahan Edirisooriya
Sahan Edirisooriya - avatar
3 odpowiedzi
+ 1
Loop through the string and use Char.IsLetter result = Char.IsLetter(ch1); This wil return a bool that tells you whether the examined item is a letter. https://www.geeksforgeeks.org/c-char-isletter-method/
10th Jan 2019, 8:27 PM
sneeze
sneeze - avatar
0
Not sure what the problem is but if I understood correctly, you can use the TryParse method. e.g success = int.TryParse(Console.ReadLine(), out int x); success is a bool which shall be true or false depending if the TryParse succeeded or not. TryParse(string, out integer) is the syntax. in a loop e.g: int x; bool success; while(!success) { Console.WriteLine(“Input: “) success = int.TryParse(Console.ReadLine(), out x); }
10th Jan 2019, 10:26 PM
Joery De Loose
Joery De Loose - avatar
0
One way you could do this is to use a Linq Query: //iterate through All elements of the string(s) //performing the operation char.IsDigit on each char contained in the string(s) if(!bushels.All(char.IsDigit)) { Console.Writeline(“Error, You should type an integer”) } with bushels.All(), you can do char.IsLetter, char.IsDigit, char.IsLetterOrDigit, etc, to check for the cases you want.
11th Jan 2019, 6:54 PM
Joshua Cade Barber
Joshua Cade Barber - avatar