Is it possible to iterate through a text file lines and use stringstream to parse each line?

32k views Asked by At

What I am trying to do is read from a text file each line while parsing using sstream library. I got the program to run but it's stuck in a loop.

Program:

string date;
int time;
float amount;

ifstream testFile("test.txt");
string token;
string line;

while(!testFile.eof()) {

    while(getline(testFile,token,',')){
        line += token + ' ';
    }
    stringstream ss(line); 
    ss >> date;
    ss >> time;
    ss >> amount;

    cout << "Date: " << date << " ";
    cout << "Time: " << time << " ";
    cout << "Amount: " << amount << " ";
    cout<<endl;

    ss.clear();

}    
testFile.close();

test.txt:

10/12/1993,0800,7.97
11/12/1993,0800,8.97

Wanted output:

Date: 10/12/1993 Time: 0800 Amount: 7.97
Date: 11/12/1993 Time: 0800 Amount: 8.97

How can I effectively produce this?

2

There are 2 answers

0
Pixelchemist On
  1. Don't loop using eof. Why is iostream::eof inside a loop condition considered wrong?

  2. Read the file line by line. Read file line by line

  3. Split the string of each line using , as a seperator. Split a string in C++?

  4. Create std::stringstream objects of the second and third strings and use operator>> to obtain the int and double values from them.

0
Paul Rooney On
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{    
    ifstream testFile("testdates.txt");    
    string line;

    while(getline(testFile, line)){

        string date;
        int time;
        float amount;

        std::replace(line.begin(), line.end(), ',', ' ');

        stringstream ss(line);

        ss >> date;
        ss >> time;
        ss >> amount;

        cout << "Date: " << date << " ";
        cout << "Time: " << std::setfill('0') << std::setw(4) << time << " ";
        cout << "Amount: " << amount << " ";

        cout << '\n';
    }   
}

You should read line by line using getline. You should check the return value of this to know when to quit (not !eof). Then you can replace all the commas with spaces and use your existing stream parse code to read the values.

Note the ss.clear() and testFile.close() are not required, as ss is recreated on each iteration and testFile is closed in its destructor.