Question

I have a file that consists of lines that look like this:

nameOfFood hh:mm PriceOfFood.

I have to count the income provided between 11:30 and 13:30 by each type of food. So the output should look like this:

nameOfFood1 yielded $$$ between 11:30 and 13:30.  
nameOfFood2 yielded $$$ between 11:30 and 13:30. 

and so on.

Currently im using an ifstream f to do this (name and time are strings, price is integer):

f >> name >> time >>price;

My question is: how can I read the HH and MM parts of the timestamp into separate (integer) variables, so I can convert them into minutes (60*HH+MM) to make them comparable?

Was it helpful?

Solution

The way the input operators work is it stops at the point in the stream that no longer matches the target (in addition to on separators, like space). So, just treat the hour and minute as integers in the input stream, but you also have to swallow the colon character.

std::istringstream f("name 19:30 234");
std::string name;
int hour;
int minute;
int price;
char c;

f >> name >> hour >> c >> minute >> price;

OTHER TIPS

Since your input format is fixed, you could do this:

std::string time = ...;
std::string hours(time, 0, 2); // start at 0, take 2 chars
std::string minutes(time, 3, 2); // start beyond ':', take 2 chars

This makes use of std::string's constructor taking another string, position, and character count.

I'll leave the actual integer conversion as an exercise.

simply you can use the c input method:

scanf("%d:%d",&H,&M);

don't forget to include stdio.h

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top