I’m trying to read a text file one line at a time and print each line to a terminal window. I’m compiling on a mac using g++, e.g., g++ cpp3.cpp -o cpp3.
The text file looks like this:
20100000001 20100000001.xml
20100000002 20100000002.xml
20100000003 20100000003.xml
20100000004 20100000004.xml
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ifs("file.txt");
string line;
while(getline(ifs,line)) {
getline(ifs,line);
cout << "[ " << line << " ]" << endl;
}
return 0;
}
I’d like the output to look like:
[20100000001 20100000001.xml]
[20100000002 20100000002.xml]
[20100000003 20100000003.xml]
[20100000004 20100000004.xml]
However, everything is printed to a single line in the terminal. In other words, each line from the text file is written on top of the last. Furthermore, the brackets, “[” and “]” appear to only be written once, so that it basically prints “[“, then the entire contents of the file, and then “]”.
So this is what the final output to the terminal looks like:
user$ ./cpp3
]10000000401 20100000004.xml
user$
Can anyone explain why this is happening and/or how to fix the problem?
Take a look at the data file – perhaps with
od -c.Everything written on top of each other line sounds as if you’re printing
\r(carriage return) and not\n(newline) in the output, maybe because the data does not contain newlines.Maybe the file comes from a Windows environment, and thegetline()is stripping the newline, leaving carriage return at the end, and the output is not reinstating the newline?Or, maybe the file only contains
\rline endings – in which case, thegetline()would read the entire file as a single line, and output it as a single line. You could demonstrate that by adding a counter to the output, incrementing it for each output line. Your observation about ‘square brackets printed once’ would suggest this might be better than the stricken suggestion. You have anendlin the output, which is important.