C++:在完成第一个输入后输入第二个输入时出错
我尝试编写程序来输入一系列数字并输入我要求和的数字。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int num;
vector<int> number;
cout << "Please enter some number (press '|' at prompt to stop):\n";
while (cin >> num)
number.push_back(num);
int n, sum = 0;
cout << "Please enter how many of the numbers you wish to sum, starting from the first:\n";
cin >> n;
}
但是,当我输入一些数字并用 '|' 停止我的第一个输入时,它会输出行 “请输入多少...” 并结束编译器,而不会输入变量n。
I try to write the program to input a series of numbers and input how many numbers I want to sum.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int num;
vector<int> number;
cout << "Please enter some number (press '|' at prompt to stop):\n";
while (cin >> num)
number.push_back(num);
int n, sum = 0;
cout << "Please enter how many of the numbers you wish to sum, starting from the first:\n";
cin >> n;
}
But when I input some number and stop my first input with '|', then it outputs the line "Please enter how many of..." and ends the compiler without inputting the variable n.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在接受最后一个参数之前添加 cin.ignore() ,以忽略添加到输入流的额外字符(当您点击 '\n' 输入您的值时,它会被添加到输入流以及您的其他无效输入可以在同一行另外添加)。可能还想添加 cin.clear() 来预先重置流状态。
另外,请注意,无论您在 while 循环中输入什么非整数,提示都会停止。
You can add cin.ignore() before taking in last argument, to ignore the extra characters that gets added to input stream (when you hit '\n' to input your value, it gets added to input stream and also other invalid inputs you may additionally add on same line). Probably want to add in cin.clear() to reset stream state beforehand as well.
Also, please note that prompt will stop no matter what noninteger you input for while loop.