gpt4 book ai didi

c++ - 来自无效输入的 std::cin 无限循环

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:40 24 4
gpt4 key购买 nike

<分区>

请阅读以下代码:

#include <iostream>
#include <cstdlib>
int main() {
std::cout << "Please input one integer." << std::endl;
int i;
while (true) {
std::cin >> i;
if (std::cin) {
std::cout << "i = " << i << std::endl;
break;
} else {
std::cout << "Error. Please try again."<< std::endl;
std::cin.ignore();
std::cin.clear();
}
}
std::cout << "Thank you very much." << std::endl;
std::system("pause");
return 0;
}

当我给 std::cin 一个无效输入时,例如 w,然后 Error。请重试。 无限输出。我认为 std::cin.ignore 会将输入流清空,而 std::cin.clear 会将其恢复到正常状态。那么为什么会出现死循环呢?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com