Search code examples
c#relational-operators

Relational Operator Statement And Output Don't Seem To Match


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


Solution

  • 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;