Reputation: 45
In C# why output of this 2 code is different from each other ?
StreamReader test = new StreamReader(@"C:\a.txt");
while (test.ReadLine() != null)
{
Console.WriteLine(test.ReadLine());
}
And this code :
StreamReader test = new StreamReader(@"C:\a.txt");
string line = "";
while ((line = test.ReadLine()) != null)
{
Console.WriteLine(line);
}
Upvotes: 3
Views: 1225
Reputation: 516
Both the code works same with little magic ,becuase of the reason:
test.ReadLine(): return: The next line from the input stream, or null if the end of the input stream is reached.
// 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);
}
Upvotes: 0
Reputation: 278
In your first example, use this code instead:
while(!test.EndOfStream)
{
Console.WriteLine(test.ReadLine());
}
Upvotes: 1
Reputation: 21400
Each time you call test.ReadLine()
you read one new line, so the first code skippes a half of them.
Upvotes: 12