Reputation: 2975
I am trying to read a File with below content:
This is Line One
This is Line Two
This is Line Three
This is Line Four
This is Line Five
Code:
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main()
{
char buff[50];
ifstream is("Test.txt");
if(!is)
cout << "Unable to open Test.txt\n";
while(is.getline(buff,50,'\n'))
{
cout << is.gcount();
cout << buff;
cout << "\n----------------\n";
}
return 0;
}
The Output:
$ ./Trial
18This is Line One
----------------
18This is Line Two
----------------
20This is Line Three
----------------
19This is Line Four
----------------
17This is Line Five
----------------
Now Suppose If I comment cout << "\n----------------\n";
i.e.
while(is.getline(buff,50,'\n'))
{
cout << is.gcount();
cout << buff;
//cout << "\n----------------\n";
}
I get Output as:
$ ./Trial
17This is Line Fivee
I am not able to figure out - why such behavior ?
Also Why showing the count as 18 (suppose first Line - Where as first line contains 16 characters including white spaces - if I add null it becomes 17 - Endof line character is discarded by getline).
I am using windows-7 and cygwin.
Upvotes: 4
Views: 1205
Reputation: 129374
The problem is definitely that each line overwrites the previous line, which in turn is caused by the fact that the newline in a Windows/DOS text file is CR+LF ("\r\n"
) - but the gygwin version of C library doesn't take CR into account when reading a line. The CR on its own will move the cursor position back to the beginning of the line.
I've never used cygwin much, but it does a good job of pretending that you are on a Unix style system when you are actually on Windows, which leads to this sort of problem at times. I don't know if there is an easy fix - running the file through dos2unix Test.txt
should do the trick tho'.
If I run this on my Linux machine, I get one long line of text, rather than each line overwriting each other.
(The extra 'e' in five is from "three" which is longer than "five")
Upvotes: 0
Reputation: 2534
It looks like each line is being printed in the same place on the screen as the previous line. Since the last line "17This is Line Five"
is one character shorter than "20 This is Line Three"
, the final 'e'
in the latter line remains, giving you the "Fivee"
.
Try printing a newline after each iteration of the while, like this:
while(is.getline(buff,50,'\n'))
{
cout << is.gcount();
cout << buff;
cout << endl; // <- std::endl means "\n"
}
Upvotes: 1
Reputation: 70402
You state:
I am using windows-7 and cygwin.
The problem is likely that your cygwin environment is reading the file in binary mode, but the file is saved in DOS text format. This means as each line is emitted, the trailing \r
character causes the next emitted line to overwrite the previous one.
The 18 output vs. 16 as you expected is because of the \r
plus the trailing \n
.
Upvotes: 3