C++ 终止循环后不接受输入的程序
我想做一个程序,计算n个整数的和。但是当我尝试运行程序时,它不接受C++ 终止循环后不接受输入的程序,c++,C++,我想做一个程序,计算n个整数的和。但是当我尝试运行程序时,它不接受val2的输入 int main() { int val1 = 0; cout << "Enter the integers (enter '|' to terminate input): "; vector<int> elements = {}; while (cin >> val1) { elements.push_back(val1);
val2
的输入
int main()
{
int val1 = 0;
cout << "Enter the integers (enter '|' to terminate input): ";
vector<int> elements = {};
while (cin >> val1) {
elements.push_back(val1);
}
cout << "Enter the number to find the sum of integers: ";
int val2;
cin >> val2;
int sum = 0;
for (int i = 0; i < val2; ++i) {
sum = sum + elements[i];
cout << "The sum of first " << val2 << " elements is " << sum << endl;
}
system("pause");
return 0;
}
intmain()
{
int val1=0;
cout>val1){
元素。推回(val1);
}
cout>val2;
整数和=0;
对于(int i=0;i
#include <limits>
#包括
在这段代码之前
cout << "Enter the number to find the sum of integers: ";
cout@zerocool当您输入“|”时,出现错误,因为此字符不是有效的整数字符。此字符仍将在输入缓冲区中。您必须忽略(跳过)它。@zerocool有一个输入错误。在std::cin.:)之后放置一个点而不是逗号。例如std::cin.clear();
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );