C++ 当我输入“时,程序进入无限循环”;9+&引用; #包括 使用名称空间std; 无效检查\u正(){ cout
您输入了不是数字的字符C++ 当我输入“时,程序进入无限循环”;9+&引用; #包括 使用名称空间std; 无效检查\u正(){ cout,c++,C++,您输入了不是数字的字符9+,并试图将它们加载到一个只能接受数字的整数变量int-pesos。Cin无法将9+转换为数字,因此它进入了失败状态,您可以通过如下更改第一个循环来检查: #include <iostream> using namespace std; void check_positive () { cout << "Number given must be positive. Please try again." << endl; }
9+
,并试图将它们加载到一个只能接受数字的整数变量int-pesos
。Cin无法将9+
转换为数字,因此它进入了失败状态,您可以通过如下更改第一个循环来检查:
#include <iostream>
using namespace std;
void check_positive () {
cout << "Number given must be positive. Please try again." << endl;
}
int main() {
int pesos, interest, compound, year;
do {
cout << "How many pesos did you deposit? ";
cin >> pesos;
if (pesos <= 0) {
check_positive();
}
} while (pesos <= 0);
do {
cout << "What is the interest? ";
cin >> interest;
if (interest <= 0) {
check_positive();
}
} while (interest <= 0);
}
do{
库特>比索;
if(cin.fail()){
因为你从不检查你的输入操作是否成功。你希望发生什么?尽可能具体。你认为什么代码处理这种情况?你认为它如何处理?已经在这里讨论过了,但是为什么第一个循环没有重复,而不是变量“比索”之后的第二个循环是否有不可接受的值?我认为这取决于cin的实现,但可能是因为cin读取9
并将其放入pesos变量,然后由于+
而进入失败状态,因为现在pesos>0
它退出第一个循环。当您试图在失败状态下使用cin读取int时兴趣
它会立即返回,无需阅读任何输入。哦,好的,谢谢您的帮助:)
do {
cout << "How many pesos did you deposit? ";
cin >> pesos;
if (cin.fail()) {
cout << "You didn't enter a number!";
return EXIT_FAILURE;
}
if (pesos <= 0) {
check_positive();
}