c++ - 输入流对象cin丢弃不合类型字符的问题

浏览:33日期:2023-03-14

问题描述

题目要求编写一个while循环语句,每次循环读入两个int并且将他们压入vector,当输入’|’后结束程序现在的问题在于题目要求输入两个不一样类型的字符

#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;}

以上程序是我能想到的一个解决方案,这时可以利用|来结束循环,但是这里存在一个问题,输入流对象会抛弃读到的第一个数字(因为1不是char类型)

input: 123 56output: 23 56

请问各位有没有其他的方解决方案,谢谢了~~~

问题解答

回答1:

搞定,存入vector就自己写了吧,问题帮你解决了。

#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;}

相关文章: