StreamReader输出

3
在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);
} 

4
请在代码中添加一个输出。 - Smit Patel
@Smit,你为什么需要输出? - Qwertiy
根据问题@Qwertiy中提到的,请将以下与编程相关的内容从英文翻译成中文。只返回翻译后的文本内容。 - Smit Patel
3个回答

12
每次调用test.ReadLine()都会读取一行新的文本,因此第一段代码跳过了其中一半。

1
在你的第一个示例中,请使用以下代码:
while(!test.EndOfStream)
{
   Console.WriteLine(test.ReadLine());
}

你的版本和第二段代码在尾随换行符方面有什么区别吗?不确定C#是否也是如此,但在C++中,不建议以这种方式检查EOF。 - Qwertiy
为什么我应该使用这个? - Manjoora
抱歉,我猜你试图从头到尾读取文件。如果你需要跳过每隔一行,你的第一个解决方案完全可以使用。 - Tomas Nilsson

0

这两段代码的作用是相同的,只是有一点小魔法,原因如下:

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);
        } 

1
请格式化您的回答。 - Qwertiy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接