C# - 循环输入直到 EOF

C# - Loop input until EOF

这是我的循环输入直到 eof 的代码:

string input;
List<string> s = new List<string>();
while((input = Console.ReadLine()) != null && input != ""){
   input = Console.ReadLine();
   s.Add(input);

}

foreach(string h in s){
   Console.WriteLine(h);
}

输入一直循环每一行,直到我按下 'ctrl-z'。每个输入都分配到列表中,但似乎并非所有输入都分配到列表中。

输出:

输出应该是:

a

b

c

d

感谢帮助;

您为每个循环调用了两次 Console.ReadLine()。 简单的解决方法是删除第二个调用。

string input;
List<string> s = new List<string>();
while((input = Console.ReadLine()) != null && input != ""){
   s.Add(input);
}

foreach(string h in s){
   Console.WriteLine(h);
}

你不妨这样写while语句:

while (!string.IsNullOrEmpty(input = Console.ReadLine())){
        s.Add(input);
    }

删除第二个 readLine 调用应该就足够了。