-5

I was trying to put the ? operator in my code instead of the usual if /else but it gave me the same result whether it's true or false?

int student_grade;
Console.WriteLine("enter the grade:");
student_grade = Console.Read();

Console.WriteLine((student_grade >= 60) ? "passed" :"failed");
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • How about debugging your program? – Uwe Keim Feb 27 '19 at 17:20
  • 1
    Did you step through in the debugger to make sure `student_grade` actually got the correct value? – Phil M Feb 27 '19 at 17:20
  • the debbuger shows no errors !!! – Seif Walid Feb 27 '19 at 17:21
  • @SeifWalid Can you print the value of student_grade also ? – freshbm Feb 27 '19 at 17:23
  • Then edit your question to include a [mcve] demonstrating the problem, complete with what input you give, and what output you get. See [ask] – Phil M Feb 27 '19 at 17:23
  • 2
    What does [`Console.Read`](https://learn.microsoft.com/en-us/dotnet/api/system.console.read?view=netframework-4.7.2) return? Hint: Do you get the correct result when you enter `1`? – Kenneth K. Feb 27 '19 at 17:26
  • 2
    I strongly recommend you read "*[Difference between Console.Read() and Console.ReadLine()?](https://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline)*". – Wai Ha Lee Feb 27 '19 at 17:26

1 Answers1

2

Console.Read returns an ASCII value of the first character in your input. Try your code with the letter "A" as input - result will be “passed", because the ASCII value for "A" is 65. It just so happens that numbers 0-9 have ASCII values 48-57, respectively; your code compares to 60, so the result is always the same.

Converting after the input will not work; you need to use Console.ReadLine(), and parse the input as int

CoolBots
  • 4,770
  • 2
  • 16
  • 30
  • 1
    I'd suggest explaining *why* `A` will give the result it does. – Wai Ha Lee Feb 27 '19 at 17:30
  • 1
    Since .NET doesn't use ASCII, "Reads the next character from the standard input stream" means the next [`Char`](https://learn.microsoft.com/en-us/dotnet/api/system.char?view=netframework-4.7.2) value (UTF-16 code unit). UTF-16 is one of several character encodings of the [Unicode](http://www.unicode.org/charts/nameslist/index.html) character set. Unicode "A" (U+0041) is encoded by UTF-16 as `'\u0041'`, which has the decimal value of 65. – Tom Blodget Feb 28 '19 at 00:44