code_master5
code_master5

Reputation: 801

C++: Why cout is printing carriage return with the strings read from a file using ifstream?

I'm trying to read a file capitals with contents as follows:

Tokyo   
33200000
New York    
17800000
Sao Paulo   
17700000
Seoul
17500000
Mexico City
17400000

The code snippet I'm using to print the file contents is:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    std::ifstream ifs("capitals");
    std::string s, s2;

    while (getline(ifs, s)) {
        getline(ifs, s2);
        cout << s  << ": "
             << s2 << endl;
    } 

    return 0;
}

But, the output I'm getting is as follows:

code_master5@Brahmaastra:~$ g++ test.cpp -std=c++17
code_master5@Brahmaastra:~$ ./a.out 
: 33200000
: 17800000  
: 17700000  
: 17500000
: 17400000y

The expected output should be of form:

Tokyo: 33200000

The last line of the original output suggests that cout is printing carriage return after printing the city name. Why is this happening?

EDIT 1: As suggested by @Qubit I used pop_back() to remove last character. The changed code is:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    std::ifstream ifs("capitals");
    std::string s, s2;

    while (getline(ifs, s)) {
        s.pop_back();
        getline(ifs, s2);
        s2.pop_back();
        cout << s  << ": "
             << s2 << endl;
    } 

    return 0;
}

The output now is:

Tokyo   : 33200000
New York    : 17800000
Sao Paulo   : 17700000
Seoul: 17500000
Mexico City: 17400000

What are these extra spaces?

EDIT 2 The problem is solved now. As suggested by @lubgr, this is happening because the file is stored in windows-style with \r at end of each line. So, I installed dos2unix and ran the following command:

code_master5@Brahmaastra:~$ dos2unix capitals 
dos2unix: converting file capitals to Unix format... 

Then, as further explained by @codekaizer, I kept those pop_back() calls to remove the trailing '\t' characters to get the expected output.

Upvotes: 2

Views: 651

Answers (1)

lubgr
lubgr

Reputation: 38267

This is caused by your capitals file, it has line ending with a carriage return (windows style), but when you print it in a non-Windows terminal, these carriage returns aren't properly handled. You have two options, either run

dos2unix captials

which will remove all carriage return characters from the line endings, or as suggested by @Qubit in the comments, you get rid of the last character inside the while loop:

while (getline(ifs, s)) {
    getline(ifs, s2);
    s.pop_back();
    s2.pop_back();

    /* ... */
}

Upvotes: 2

Related Questions