Adam_G
Adam_G

Reputation: 7879

C++ Issue Reading Text File

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

Upvotes: 1

Views: 747

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72449

You use an implementation that uses UNIX line endings (\n), and interprets \r to return the cursor to the beginning of the line. The file contains old Mac OS line endings (\r), which means that getline() reads till the end of the file and puts all the \r into the string, causing you to print them later to the console.

Upvotes: 5

Related Questions