Console.In.Peek()返回-1进入Console、In、Peek

由网友(开心就好)分享简介:我本来期望下面的C#程序仅打印EOF!有一次我在控制台中按下Ctrl-Z。相反,程序只要我按Enter键完成:I would have expected the following C# program to only print "EOF!" once I hit "Ctrl-Z" in the console....

我本来期望下面的C#程序仅打印EOF!有一次我在控制台中按下Ctrl-Z。 相反,程序只要我按Enter键完成:

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!");

例如:

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.

我怎样才能读取超过1线路输入,从Console.In一个字符的时间?

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()返回-1 EOF,所以,你可以这样做:

Console.In.Read() returns -1 on EOF, So you can do this:

int c;
while((c = Console.In.Read()) != -1)
Console.Out.Write((char)c);
阅读全文

相关推荐

最新文章