开发者

Why won't this do-while loop break out once the condition is not met? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldw开发者_StackOverflow中文版ide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜