I’m learning C# for one of my classes and for my assignment I need to get user input from the console.
In my program I have:
choice = (char)System.Console.Read();
Later on in the program I use
if (System.Console.ReadLine() == "y")
to get input from the user.
The second statement gets skipped when I run the program. I’m guessing that the System.Console.Read() is leaving a newline in the stream. In C/C++, there’s fflush() and cin.ignore(). What is the equivalent function in C#?
I know that it’s probably easier for me to use ReadLine() or ReadKey(), but I’m just curious as to how to use Read() with newlines
Yes, console input is buffered by the operating system. The Read() call won’t return until the user presses Enter. Knowing this, you could simply call ReadLine() afterwards to consume the buffer. Or use ReadLine() in the first place.
Or the dedicated method that returns a single keystroke: Console.ReadKey()
You however don’t want to use it if you ever expect your program to be used with input redirection. Which is the reason that there’s more than one way to, seemingly, achieve the same goal: ReadKey() bypasses the stdin input stream, the one that gets redirected. It talks to the low-level console support functions directly. There’s a way to detect this so you can support both, check this answer.