在C#中,为什么这两个代码的输出是不同的?
StreamReader test = new StreamReader(@"C:\a.txt");
while (test.ReadLine() != null)
{
Console.WriteLine(test.ReadLine());
}这段代码是:
StreamReader test = new StreamReader(@"C:\a.txt");
string line = "";
while ((line = test.ReadLine()) != null)
{
Console.WriteLine(line);
} 发布于 2016-02-08 18:59:04
每次调用test.ReadLine()都会读取一行新行,因此第一段代码会跳过其中的一半。
发布于 2016-02-08 19:02:24
在您的第一个示例中,改用以下代码:
while(!test.EndOfStream)
{
Console.WriteLine(test.ReadLine());
}发布于 2016-02-08 20:26:07
由于以下原因,这两个代码的工作方式都是一样的,只是有一点魔力:
test.ReadLine(): :返回输入流的下一行,如果到达输入流的末尾,则返回null。
// So,Let's say your a.txt contain the following cases:
case 1:"Hello World"
while (test.ReadLine() != null)
{
Console.WriteLine("HI" + test.ReadLine());
}
// since,we have only one line ,so next line is null and finally it reached the EOD.
case 2:"Hello World"
"I am a coder"
while (test.ReadLine() != null)
{
Console.WriteLine("HI" + test.ReadLine());
}
// since,we have two line so ,next line is "I am a coder".
//It returns:Hi I am a coder.
// And in the below code we are reading and assigning to string variable
StreamReader test1 = new StreamReader(@"D:\a.txt");
string line = "";
while ((line = test1.ReadLine()) != null)
{
Console.WriteLine(line);
} https://stackoverflow.com/questions/35267941
复制相似问题