程序在终止循环后不接收输入

program not taking an input after terminating a loop

本文关键字:输入 终止 循环 程序      更新时间:2023-10-16

我正在尝试制作一个计算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);
}
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;
}

包含标题

#include <limits>

在此代码片段之前

cout << "Enter the number to find the sum of integers: ";

std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );

问题是输入符号'|'输入流处于错误状态,您需要跳过输入缓冲区中的非数字符号。