问题描述
目前正在学习C ++,新手。
以'|'结尾的输入时出现问题字符,我的程序跳到末尾,并且不允许进一步输入。我相信这是因为std :: cin由于在期望int时输入了char而处于错误状态,所以我尝试使用std :: cin.clear()和std :: cin.ignore()来清除问题,并允许程序的其余部分运行,但我仍然无法破解它,任何建议都值得赞赏。
int main()
{
std::vector<int> numbers{};
int input{};
char endWith{ '|' };
std::cout << "please enter some integers and press " << endWith << " to stop!\n";
while (std::cin >> input)
{
if (std::cin >> input)
{
numbers.push_back(input);
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
}
然后将向量传递给函数以迭代x次,然后将每个元素添加到总计中,但是程序总是跳过用户输入:
std::cout << "Enter the amount of integers you want to sum!\n";
int x{};
int total{};
std::cin >> x;
for (int i{ 0 }; i < x; ++i)
{
total += print[i];
}
std::cout << "The total of the first " << x << " numbers is " << total;
请帮助!
解决方法
当用户输入“ |”时(或不是int
的任何内容),循环结束并且循环内的错误处理不执行。只需将错误代码移到循环外即可。另外,您从stdin
读取了两次,这将跳过其他所有int。
while (std::cin >> input) {
numbers.push_back(input);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
注意:如果要专门检查“ |”可以更改为以下内容:
while (true) {
if (std::cin >> input) {
numbers.push_back(input);
}
else {
// Clear error state
std::cin.clear();
char c;
// Read single char
std::cin >> c;
if (c == '|') break;
// else what to do if it is not an int or "|"??
}
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');