I would have expected the following C# program to only print “EOF!” once I hit “Ctrl-Z” in the console.
Instead, the program finishes as soon as I hit Enter:
var textReader = Console.In;
var sb = new StringBuilder();
while(textReader.Peek() != -1)
{
sb.Append((char)textReader.Read());
}
Console.WriteLine("Entered: '{0}'", sb);
Console.WriteLine("EOF!");
Example:
12345 <= I entered this
Entered: '12345 <= program outputs this
'
EOF!
Press any key to continue . . .
Can anyone explain the above behaviour? It’s not at all what I expected.
How can I read more than 1 line of input from Console.In one character at a time?
Update: As answered below: The issue is that Peek() can’t be relied on. Using Read() works though.
Console.In.Read() returns -1 on EOF, So you can do this: