Flushing System.Console.Read()
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 w开发者_如何学JAVAhen 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
This is my equivalent for fflush:
while (Console.KeyAvailable)
Console.ReadKey(true);
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.
class Program
{
static void Main(string[] args)
{
if (Console.ReadLine() == "y")
Console.WriteLine("You typed y");
Console.ReadLine();
}
}
You can also do
if (Console.ReadLine().ToLower() == "y")
Console.WriteLine("You typed y");
if you are doing char c = (char) Console.Read(); then whatever you type for Console.Read .. you have to continue entering the statement for Console.Readline() right next to it for Console.Readline to work.
Alternatively you can use if (Console.ReadLine().ToLower().Trim() == "y")
But for this to work you type something for Console.Read()
like input value N and then you have to type y after some spaces for next Console.ReadLine to evaluate.
Like this.
n y
class Program
{
static void Main(string[] args)
{
char c = (char)Console.Read();
if (Console.ReadLine().ToLower().Trim() == "y")
Console.WriteLine("You typed y");
Console.ReadLine();
}
//input: n y
//output: You typed y
}
There is something barely close to flush which is Console.Clear() method but this also clears the display as well as buffer.
精彩评论