-5

So i am currnently trying to get into programming with C# with absolutely no expierience whatsoever. So i tried making a simple program that reads user input and outputs it again to the user. Now the name part is all fine, but when i try to input my age as for ex. 20 y/o, it always writes "Your input has been saved. You are 49 Year(s) old." Whatever number i put in, it always gives me 49, and i can't see any problem in the code that would cause this. Do you know what's wrong?

        Console.Write("Insert Age: ");
        int age = Convert.ToInt32(Console.Read());
        if (age < 18)
        {
            Console.WriteLine("Whoops! Looks like you are only " + age + " Year(s) old! You are too young to have your input saved.");
        }
        else
        {
            Console.WriteLine("Your input has been saved. You are " + age + " Year(s) old.");
        }
  • 2
    Try Console.ReadLine instead of .Read. .Read reads a character, not a string, and when you convert a character to an int you get its code point value, at least for these characters. 0 is code point 48, 1 is 49, and so on. – Lasse V. Karlsen Sep 04 '18 at 17:30
  • `for ex. 20 y/o` It should be giving you `50` for an input of `20`. See www.asciitable.com – Ňɏssa Pøngjǣrdenlarp Sep 04 '18 at 17:32
  • 1
    As a beginner, one of the first things you should learn is that conversions *look* simple but are the cause of **so** many issues. Any time you use `Convert`, or insert a cast, etc, you should make sure you have a rock solid understanding of why you're doing it. Far too many beginners throw conversions at code that won't compile (or just insert `.ToString()` everywhere, which is equivalent) without trying to understand. – Damien_The_Unbeliever Sep 04 '18 at 17:36
  • [Difference between Console.Read() and Console.ReadLine()](https://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline) – janniks Sep 04 '18 at 17:37
  • 1
    Storing the result of `Console.Read()` into a variable before converting it would make the issue easier to see. The variable would contain only a single character. –  Sep 04 '18 at 17:38
  • 2
    Any time you don't understand what a method is doing, the first thing you should do is [read its documentation](https://learn.microsoft.com/en-us/dotnet/api/system.console.read?view=netframework-4.7.1#System_Console_Read). – Dour High Arch Sep 04 '18 at 17:39
  • 2
    Possible duplicate of [How can I read user input from the console?](https://stackoverflow.com/questions/7280591/how-can-i-read-user-input-from-the-console) – 41686d6564 stands w. Palestine Sep 04 '18 at 18:58

3 Answers3

1

Console.Read() method read just a single character from the console. If you want to read a number, 20 or 77 for example, you need Console.ReadLine() method. This will read for the entire line which will contain your number.

I strongly recommend you to use int.TryParse() method instead of Convert.ToInt32() method because in some cases the conversion will fail. For example if someone type the input in the wrong format and he will introduce this line: 20a. Then your program will crash.

To use int.TryParse() method is very simple. Your code will looks like this:

    Console.Write("Insert Age: ");
    if( true == int.TryParse(Console.ReadLine()) )
    {
       if (age < 18)
       {
          Console.WriteLine("Whoops! Looks like you are only " + age  
                          + " Year(s) old! You are too young to have your input saved.");
       }
       else
       {
          Console.WriteLine("Your input has been saved. You are " 
                             + age + " Year(s) old.");
       }
    }
    else
    {
       Console.WriteLine("This is not a number."); // Or any message you want
    }

To make this code shorter you can try to write something like this:

    Console.Write("Insert Age: ");
    if( true == int.TryParse(Console.ReadLine()) )
    {
       Console.WriteLine( age < 18 ? 
         "Whoops! Looks like you are only " + age + 
         " Year(s) old! You are too young to have your input saved." :
         "Your input has been saved. You are " + age + " Year(s) old.");
    }
    else
    {
       Console.WriteLine("This is not a number."); // Or any message you want
    }

And if you want to be even shorter then try:

    Console.Write("Insert Age: ");
    Console.WriteLine( int.TryParse(Console.ReadLine()) ?
       (age < 18 ?
            "Whoops! Looks like you are only " + age 
             + " Year(s) old! You are too young to have your input saved." 
         : "Your input has been saved. You are " + age + " Year(s) old.") 
      : "This is not a number.");
Kjartan
  • 18,591
  • 15
  • 71
  • 96
Ionut Enache
  • 461
  • 8
  • 22
0

Console.Read() reads only the next character from standard input, and Console.ReadLine() reads the next line of characters from the standard input stream.


Source verbatim from @VMAtm: Difference between Console.Read() and Console.ReadLine()?

janniks
  • 2,942
  • 4
  • 23
  • 36
0

the issue is a basic understanding problem. .NET does everything fine here.

Please have a look on the Console.Read() method. As you can see, it returns an Int32 value. Meaning, in your case: it reads the first char of the input stream. If you enter "23" in the console, then the 2 is considered to be a char, which represents, according to ASCII, the value 50. After that, you take this 50 and convert it to an Integer: age = 50.

Possible Solution

According to MSDN

int age = Convert.ToInt32(Console.ReadLine());

Hope that helps.

movcmpret
  • 179
  • 1
  • 10
  • Just to add clarification to this answer, **only** the `2` is used, because it only reads one character at a time. The `Read()` method already returns an integer so no conversion is necessary there. The `ReadLine()` method on the other hand returns a string, so the value needs to be converted to an integer. – JuanR Sep 04 '18 at 17:59