c++ - Problem with input stream object cin discarding untyped characters
仅有的幸福
仅有的幸福 2017-06-27 09:19:12
0
1
1044

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~~~

仅有的幸福
仅有的幸福

reply all(1)
洪涛

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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template