英文:
C++ - cin is skipping input without any user input
问题
#include <iostream>
#include <vector>
using namespace std;
int main() {
int userinput;
int sums;
int sum = 0;
vector<int> nums;
cout << "Enter as many numbers as you'd like." << endl;
while (cin >> userinput) {
nums.push_back(userinput);
}
cout << "Enter the numbers you want to add: ";
cin >> sums;
for (int i = 0; i < sums; ++i) {
sum += nums[i];
}
cout << "The sum of the first " << sums << " numbers is: " << sum << "." << endl;
return 0;
}
我的问题是,在接受变量 sums 的输入行上,每当我运行代码时,都会跳过这个输入行,sums 只设置为1,没有我的输入。我尝试过 cin.clear(),因为我听说它可能会修复它,但都没有成功。
英文:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int userinput;
int sums;
int sum = 0;
vector<int> nums;
cout << "Enter as many numbers as you'd like." << endl;
while (cin >> userinput) {
nums.push_back(userinput);
}
cout << "Enter the numbers you want to add: ";
cin >> sums;
for (int i = 0; i < sums; ++i) {
sum += nums[i];
}
cout << "The sum of the first " << sums << " numbers is: " << sum << "." << endl;
return 0;
}
My problem is that on the line where I take input for the variable sums, whenever I actually run the code, this input line is skipped over and sums just gets set to 1 without any of my own input. I'm sorry if this is a really stupid question but I have nowhere else to ask as I am trying to learn myself.
I've tried cin.clear() because I've heard that could fix it but none of them worked.
答案1
得分: 0
while (cin >> userinput)
只有在 cin
评估为 false
时才会退出。cin
仅在处于错误状态时评估为 false
,这将阻止使用 cin
进行任何进一步的操作。您必须在要求用户的下一个输入之前使用 cin.clear
来清除错误状态:
cout << "输入您要相加的数字:";
cin.clear();
cin >> sums;
正如评论中所提到的,如果用户可以输入某个值来告诉程序他们已经停止输入数字,会更好。例如:
while (cin >> userinput) {
if (userinput == -1 /* 或您想要的任何值 */) break;
nums.push_back(userinput);
}
以这种方式中断循环允许退出循环,而无需将 cin
设置为错误状态(这也可以说是更好的设计)。
英文:
The only way that while (cin >> userinput)
will be exited is if cin
evaluates to false
. cin
evaluates to false
only if it's in an error state, which would prevent any further operations using cin
. You have to clear the error state with cin.clear
before you ask for the next input from the user:
cout << "Enter the numbers you want to add: ";
cin.clear();
cin >> sums;
As the comments have said, it would be better if the user could input some value to signal to the program that they've stopped inputting numbers. For example:
while (cin >> userinput) {
if (userinput == -1 /* or whatever value you want */) break;
nums.push_back(userinput);
}
Breaking the loop this way allows the loop to be exited without setting cin
to be in an error state (it's also arguably better design).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论