简体   繁体   中英

Ifstream.getline() - Only reading first line?

I'm just trying to run a simple c++ program that will format a .txt file with data entries. I have run it with many different text files of the exact same format, and now it just won't work. I'm sure the solution is simple.

Here is a simplified version of the program (I trimmed down everything to only show the parts that are giving me trouble).

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

int main(){

    ifstream filei("in.txt");
    ofstream fileo("comlab.txt");
    double a, b;
    string s;
    stringstream ss;

    while (getline(filei,s)){
        ss<<s;
        ss>>a>>b;
        fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
    }

    fileo.close();
}

Here is a sample input for in.txt :

1        11
2        22
3        33
4        44
5        55

Now here is what I want to show up (exactly the same as input):

1        11
2        22
3        33
4        44
5        55

But here is what actually shows up:

         1        11
         1        11
         1        11
         1        11
         1        11

What is going on? I'm compiling with g++ and following the C++11 standard.

When you execute

    ss>>a>>b;

in the first round of execution of the loop. ss is already at the end of the stream. ie ss.eof() == true . You need to clear its state and reset state to start reading from the beginning.

while (getline(filei,s)){
    ss<<s;
    ss>>a>>b;
    ss.clear();
    ss.seakg(0);
    fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
}

A better alternative is to create the object within the scope of the loop.

while (getline(filei,s)){
    stringstream ss;
    ss<<s;
    ss>>a>>b;
    fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
}

or even simpler (Thanks to @vsoftco for the suggestion)

while (getline(filei,s)){
    stringstream ss(s);
    ss>>a>>b;
    fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM