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

Chuck picture Chuck · Jan 4, 2017 · Viewed 16.3k times · Source

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?

Answer

Pixelchemist picture Pixelchemist · Jan 4, 2017
  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.