string stream of ints trailling with a space/carriage return/tab results in re-streaming of last int in C++

28 Views Asked by At

this error occuars with any (or mix) of mentioned characters in title but I will talk about spaces for easier reading.

A textfile names input.txt conatins space seprated ints, ex:

2 3 
4 1 
5 4 1 

each has line has a trailling space I need to diffrinacte between lines so I use getline

int main()
{
    string input;
    stringstream ss;
    ss.clear();ss.str("");
    int  no_lines = 3;
    int tmp;

    for(int i = 0; i < no_lines; i++)
    {
        getline(cin, input);
        ss.clear();
        ss.str(input);
        while(!ss.eof())
        {
            ss >> tmp;
            cout << tmp << ' '; 
        }
        cout << endl;
    }
}

and I ran the program with a.out < input.txt expected output is the same as input.txt but rather I get this:

2 3 3 
4 1 1 
5 4 1 1

every last int is reapeated.

0

There are 0 best solutions below