Tommy Yap
Tommy Yap

Reputation: 101

c++ missing data while reading from file

Hi guys sry to trouble you. I have 2 problems.

  1. I having problem printing out the last data in my file
  2. How can i print out only certain row start with the username

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

Answers (2)

Mohit Jain
Mohit Jain

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;
}

Live code here

  • Adding 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 :
  • Change data2 to data1 to get first name
  • To print conditionally, use an if before cout statement

if(data1 == "tom12") cout << data1 << " $" << data3 << " " << data4 << " "<< endl;

Upvotes: 2

Wintermute
Wintermute

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

Related Questions