Search code examples
c#if-statementconsole.readline

Console.Read with int


I was studying c# one and a half ear ago. And I forgot a lot. Now I want to study it again. I wanted to do

        int answer;
        Console.WriteLine("What is the answer?");
        answer = Console.Read();
        if(answer == 1)
        {
            Console.WriteLine("You are good!");
        }
        else
            Console.WriteLine("You are dumb!");

And in the console I have this: enter image description here or enter image description here

Guys help please!!


Solution

  • It's better to use the Console.ReadLine(). This way you can get more characters.

    To parse it as an int, you use the int.TryParse()

    example

    int answer;
    string answerStr;
    Console.WriteLine("What is the answer?");
    answerStr = Console.ReadLine();
    
    if(int.TryParse(answerStr, out answer))
    {
        if(answer == 1)
        {
            Console.WriteLine("You are good!");
        }
        else
            Console.WriteLine("You are dumb!");
    }
    else
        Console.WriteLine("You are even dumber! That's not a number!");