简体   繁体   中英

C++: Why does this code run an endless loop if the input was not integral?

I have this simple code that duplicate a string by using either a reference or a pointer (I'm a beginner), and I would like to make it determine whether the input is integral or not because if it wasn't, it keeps looping for some reason. I've tried using cin.clear() but it doesn't seem to work.. Here is the code:

#include <iostream>
#include <string>
#include "test.h"
using namespace std;
int main() {
    while (true) {
        cout << "Type something: ";
        string hi;
        cin >> hi;
        cout << "Choose a method to change it:\n1. By reference.\n2. By using pointers.\n";
    start:
        int i;
        cin >> i;
        if (cin.fail())
            cin.clear();
        switch (i) {
        case 1:
            changestringref(hi);
            cout << hi << '\n';
            break;
        case 2:
            changestringptr(&hi);
            cout << hi << '\n';
            break;
        default:
            cout << "Choose by typing either 1 or 2: ";
            goto start;
            break;
        }
    }
}

Whenever I type a string (at the second input), it keeps looping this sentence: "Choose by typing either 1 or 2: Choose by typing either 1 or 2: Choose by typing either 1 or 2: "etc. How can I solve this problem? And why isn't cin.clear working? isn't it supposed to clear the input from the last time cin was used or am I wrong? Oo

Thanks in advance :D

And why isn't cin.clear working? isn't it supposed to clear the input from the last time cin was used or am I wrong?

Not quite. It's supposed to Set[s] a new value for the stream's internal error state flags. . clear() without argument sets goodbit and clears the fail() state, but leaves any unprocessed input untouched.

Let's assume you entered 'x' . Since 'x' is not a number, cin >> i sets failbit , and does not consume input (actually, it pushes the already consumed x back into the input buffer, but that's another story).

This is behavior documented somewhat obscurely in num_get::get() . The returned iterator (ie the stream) points right before the first character that could not be parsed.

So next time, after the goto start; you read x again. Same input, same result, hence the endless loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM