Home  >  Q&A  >  body text

c++ - Problem with input stream object cin discarding untyped characters

The question requires writing a while loop statement. Each loop reads two ints and pushes them into the vector. When '|' is entered, the program ends.
The problem now is that the question requires the input of two different types. character

#include <iostream>

using namespace std;

int main() {

    int num_1, num_2;
    char stop;
    while (cin >> stop) {
        if (stop == '|') {
            break;
        } else {
            cin >> num_1 >> num_2;
            cout << num_1 << " " << num_2 << endl;
        }
    }

    return 0;
}

The above program is a solution I can think of. At this time, you can use | to end the loop, but there is a problem here. The input stream object will discard the first number read (because 1 is not a char type)

input: 123 56
output: 23 56

Do you have any other solutions? Thank you~~~

仅有的幸福仅有的幸福2693 days ago986

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-06-27 09:21:12

    Get it done, save it in the vector and write it yourself, the problem is solved for you.

    #include <iostream>
    using namespace std;
    
    
    int main(int argc, const char * argv[]) {
        int num_1, num_2;
        char stop;
        while (cin >> stop) {
            if (stop == '|') {
                break;
            } else {
                num_1 = stop-'0';
                cin >> num_2;
                cout << num_1 << " " << num_2 << endl;
            }
        }
        return 0;
    }

    reply
    0
  • Cancelreply