+ 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
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/
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);
}
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.