1

Good day all, I'm new to C# and currently at the stage of experimenting with if-else statements. Upon declaring variables ageUser, permittedAge, input and running the program, I noticed that the if statement and the resulting output don't seem to match.

        int ageUser;
        int permittedAge = 18;
        int input;

        Console.Write("Put in your age: ");
        input = Convert.ToInt32(Console.Read());
        ageUser = input;

        if (ageUser < permittedAge)
        {
            Console.WriteLine("Sorry you are not permitted to enter this site!");
        }

        else
        {
            Console.WriteLine("Welcome");
        }

Link To Console Output

Danny
  • 23
  • 4
  • 2
    `Convert.ToInt32(Console.Read());` should be `int.Parse(Console.ReadLine());`. You should have spotted the wrong result when debugging the value of `ageUser` – UnholySheep Dec 31 '19 at 22:45
  • Hello Danny. I think that you must use Console.ReadLine instead of Console.Read. Console.Read read only one character. – Jean-Claude Colette Dec 31 '19 at 22:47
  • Thanks @Jean-ClaudeColette for the clarification. – Danny Dec 31 '19 at 23:09
  • @UnholySheep If I may ask, when is it appropriate to use `Convert.ToInt32(Console.Read());` and `int.Parse(Console.ReadLine());`? – Danny Dec 31 '19 at 23:18
  • I can't think of any case where `Convert.ToInt32(Console.Read());` would be the right thing to use, but there's probably some use case. In most cases you want to read user input using `Console.ReadLine()` (and `int.Parse` vs `Convert.ToInt32` is a different discussion: https://stackoverflow.com/questions/199470/whats-the-main-difference-between-int-parse-and-convert-toint32) – UnholySheep Dec 31 '19 at 23:24

1 Answers1

1

You will need to change how you read in the input. Read() reads in a character and does not convert that to int like you think it does. (5 becomes 53 due to its ASCII representation). Use ReadLine instead.

Use the folowing instead.

    Console.Write("Put in your age: ");
    input = Convert.ToInt32(Console.ReadLine());
    ageUser = input;
Jawad
  • 11,028
  • 3
  • 24
  • 37