1

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.

Arturo don Juan
  • 249
  • 2
  • 8
  • If you're assuming that the problem is with `getline`, that assumption is wrong. Fire up the debugger. – chris Feb 17 '15 at 17:49

1 Answers1

3

When you execute

    ss>>a>>b;

in the first round of execution of the loop. ss is already at the end of the stream. i.e. 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';
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270