I’m trying to pick up C++, and am getting the error below, when reading a text file. Any idea why?
Input:
This is a test.
A test, with tabs and too many spaces.
If this is a good one,
then all will be well.
Output:
then all will be well. too many spaces.
Code:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream infile ("A5.txt");
if (infile.is_open()) {
while (!infile.eof()) {
getline(infile,line);
cout << line << endl;
}
infile.close();
}
return 0;
}
You use an implementation that uses UNIX line endings (
\n), and interprets\rto return the cursor to the beginning of the line. The file contains old Mac OS line endings (\r), which means thatgetline()reads till the end of the file and puts all the\rinto the string, causing you to print them later to the console.