Steve Deng Zishi
Steve Deng Zishi

Reputation: 128

piping input file from bash and read it line by line using getline(cin,line)

I am trying to read the file using getline() function and piping my input file using bash command but get illogical output.

This is my main.cpp code:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;
int main(int argc, const char * argv[]) {

    string line;

    while(getline(cin,line)){
        cout<<line<<endl;
    }
    return 0;
}

My input file named input.txt look like this

4 MF MF FM FF MF MM
MM FF
MF MF MF MF FF

My bash command and running result

DENGs-MacBook-Pro:APS stevedeng$ g++ -o main main.cpp -std=c++11
DENGs-MacBook-Pro:APS stevedeng$ ./main < input.txt
MF MF MF MF FFMF MM

What I thought is that the program will read the input.txt line by line and print the output exactly as the format as the input file.

Can someone explain what is happening here with the only one line of wired looking output?

How can I achieve the result of reading it line by line if the only way I can do is piping the input file from bash instead of using ifstream? Any help will be appreciated.

Upvotes: 0

Views: 1684

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35164

It seems as if your terminal does not receive or neglect the line feed, such that every new line overwrites the previously written one.

One thing could be that the input file contains only the carriage return but now line feed, and for some reason getline does not correct this. If this is the issue, see the following answer on SO (please don't forget to upvote if helpful).

Another thing could be that the line feed is not written to cout. I'd suggest - at least for diagnostic purpose - to try printf("%s\r\n",line.c_str()).

Upvotes: 1

Related Questions