Reputation: 101
Hi guys sry to trouble you. I have 2 problems.
Data:
tom12:Miscellaneous:-30.52:20JAN15
ben23:Utility Bill:-56.50:17JAN15
tom12:Child Needs:-80.95:15JAN15
tom12:Baby needs:-20.9:18JAN15
ben23:Phone Bill:-35.90:12JAN14
ben23:Housing Bill:-192.88:01JAN15
Code:
string line;
ifstream file("expenses.txt");
double totalNegative = 0;
double totalPositive = 0;
while(getline(file, line))
{
stringstream linestream(line);
string data1;
string data2;
double data3;
string data4;
getline(linestream, data1, ':');
getline(linestream, data2, ':');
linestream >>data3;
getline(linestream, data4, ':');
cout << data2 << " $" << data3 << " " << data4 << " "<< endl;
}
Results:
Miscellaneous $-30.52
Utility Bill $-56.50
Child Needs $-80.95
Baby needs $-20.9
Phone Bill $-35.90
Housing Bill $-192.88
The results are missing the dates at the last column. And how do i print out only "tom12" which is the user. Thanks!
Upvotes: 2
Views: 392
Reputation: 30489
Change your code to
{
stringstream linestream(line);
string data1;
string data2;
double data3;
string data4;
getline(linestream, data1, ':');
getline(linestream, data2, ':');
linestream >>data3;
linestream.ignore(1); // ignore ':'
getline(linestream, data4, ':');
cout << data1 << " $" << data3 << " " << data4 << " "<< endl;
}
linestream.ignore(1);
would ignore 1 character. Otherwise when you try to read the date until :
, you end up reading nothing as the first character is :
if(data1 == "tom12") cout << data1 << " $" << data3 << " " << data4 << " "<< endl;
Upvotes: 2
Reputation: 44063
After
linestream >>data3;
you still have a colon plus the last token in the stream. For example, in the case of the first line
tom12:Miscellaneous:-30.52:20JAN15
what you have left in the stream is
:20JAN15
because you consumed everything up to and including -30.52
. In this state,
getline(linestream, data4, ':');
will give you everything before the next :
, which is the empty string.
Depending on how you want to handle misshapen data, there are several ways to resolve it; perhaps the easiest is
getline(linestream, data4, ':'); // consume that colon (and possibly things left before it)
getline(linestream, data4); // then take the rest of the line.
Upvotes: 1