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?
Don't loop using
eof
. Why is iostream::eof inside a loop condition considered wrong?Read the file line by line. Read file line by line
Split the string of each line using
,
as a seperator. Split a string in C++?Create
std::stringstream
objects of the second and third strings and useoperator>>
to obtain theint
anddouble
values from them.