Console.Read with int

379 Views Asked by At

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!!

2

There are 2 best solutions below

1
Jeroen van Langen On BEST ANSWER

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!");
0
Ibrahim Timimi On

When you read char 1 from console, it equals int 49 as seen from the table below:

char     code
0 :      48
1 :      49
2:       50
...
9:       57

In your example it is better to use switch case rather than if-else.

static void Main(string[] args)
{
    Console.WriteLine("What is the answer?");
    var answer = Console.Read();
    switch (answer)
    {
        case 49: // 1
            Console.WriteLine("You are good!");
            break;
        default:
            Console.WriteLine("You are dumb!");
            break;
    }
    Console.WriteLine("Press Any key To Continue...");
}

Alternatively, you can use this to convert char to int automatically.

Console.WriteLine("What is the answer?");
var answer = Console.ReadKey().KeyChar;
Console.WriteLine();

switch (char.GetNumericValue(answer))
{
    case 1:
        Console.WriteLine("You are good!");
        break;
    default:
        Console.WriteLine("You are dumb!");
        break;
}