-1

This is a very simple script I am trying to figure out and I have been looking for a simple answer and can't find it in the forums or in my C# book.

Console.Write("Enter a Number\n");
int input = Convert.ToInt32(Console.ReadLine()); //convert code to an integer

if (!Int32.IsNumber(input)) //if not a whole number input give an error
{
    Console.WriteLine("Not an integer");
}

It's just that simple what I'm trying to do. This is a snippet from a bigger code.

venerik
  • 5,766
  • 2
  • 33
  • 43
DDJ
  • 807
  • 5
  • 13
  • 31
  • 1
    What's your question? Have you tested the code? Does it work? If not, please post the exact error message you get or behaviour you see. – Bernhard Barker Sep 26 '15 at 19:18
  • 2
    take a look at `int.TryParse` this is probably what you are looking for. It convert the the string to an integer an told you if conversion was successful or not. – tigrou Sep 26 '15 at 19:20
  • possible duplicate of [Check if user input is a number](http://stackoverflow.com/questions/14304591/check-if-user-input-is-a-number) – Bernhard Barker Sep 26 '15 at 20:04
  • [How to identify if a string is a number?](http://stackoverflow.com/questions/894263/how-to-identify-if-a-string-is-a-number) [How can I check if a string is a number?](http://stackoverflow.com/questions/6733652/how-can-i-check-if-a-string-is-a-number) [C# testing to see if a string is an integer?](http://stackoverflow.com/questions/1752499/c-sharp-testing-to-see-if-a-string-is-an-integer) [How to validate user input for whether it's an integer?](http://stackoverflow.com/questions/5395630/how-to-validate-user-input-for-whether-its-an-integer) – Bernhard Barker Sep 26 '15 at 20:06
  • With C# it won't run because of the debugger, not unless the code is correct. I will use the TryParse command. I wasn't sure if that was the only way, but it looks like it is. Thanks! – DDJ Sep 27 '15 at 00:07

2 Answers2

10
Console.Write("Enter a Number\n");
string input = Console.ReadLine(); //get the input
int num = -1;
if (!int.TryParse(input, out num))
{
    Console.WriteLine("Not an integer");
}
else
{
   ...
}

Int.TryParse will return false if the string is not a valid integer and vise versa

Steve
  • 11,696
  • 7
  • 43
  • 81
  • It only works if I do if (!int.TryParse(input, out num)). A lowercase int, but then it doesn't work right. It doesn't show the custom error – DDJ Sep 27 '15 at 00:27
  • 1
    Error when using a capital I in 'Int' "The name 'Int' does not exist in the current context" – DDJ Sep 27 '15 at 00:29
  • @SDJ fixed, use the lower case int instead – Steve Sep 27 '15 at 01:42
1

I figured out the easiest and best code to get this done from many answers:

Console.Write("\nEnter a Whole Number (Such as 12)\n");
string Input = Console.ReadLine();

char firstChar = Input[0];
bool isNumber = Char.IsDigit(firstChar);

if (!isNumber)
{
     Console.WriteLine("Not an integer");
} 
else 
 {
.......
}
DDJ
  • 807
  • 5
  • 13
  • 31