what's up, I've got another issue with this huge project I'm working on.
The project is for school, but this isn't the entire piece. For more information on the project you can look here.
So I have to take input from the user in the following format:
p 11:45 12:15
It will always start with either a p
or an s
and will have two times during which there is a call on a phone. The big idea is to compare cell phone plans taking into account daytime minutes, night minutes, etc.
Right now I'm having trouble taking the input. Every time I run the program, it doesn't care if I start the input with an s
and just keeps waiting for more data. Frustrating part is that it was working not too long ago.
Here's my code:
string c;
string end = "s";
string start = "p";
int temp_start_hour;
int temp_start_min;
int temp_end_hour;
int temp_end_min;
char colon;
do {
cin >> c;
cout << c << endl;
if (c != start && c != end)
{
cout << "ERROR IN INPUT" << endl;
return 1;
}
if (c != end)
{
cin >> temp_start_hour >> colon >> temp_start_min;
cin >> temp_end_hour >> colon >> temp_end_min;
begin_hours[i] = temp_start_hour;
begin_min[i] = temp_start_min;
end_hours[i] = temp_end_hour;
end_min[i] = temp_end_min;
}
i++;
} while (c != end);
Your code (with a couple tweaks to make it compile) is working fine for me. Could you post the input you are sending to it that causes the program to fail?
If your input stream gets into an error state your loop will never end. That's because if its in an error state, nothing will get written into any variable used in cin >> c
and c
will keep its last value forever.
To fix this you should really use a while(cin)
loop instead of a do-while loop, or check if( cin.fail() )
after cin >> c
.
Or you could call cin.exceptions ( ifstream::failbit | ifstream::badbit )
before starting the loop. That would enable a C++ exception thrown from the stream input function if anything goes wrong.
精彩评论