[英]I can't call a function in else if statement
#include <iostream>
#include <vector>
void Invalid_input(int& num1, int& num2)
{
while (!cin)
{
cout << "You entered an incorrect value!" << '\n';
cin.clear();
cin.ignore(100, '\n');
cout << "Please input again : ";
cin >> num1 >> num2;
}
}
int main() {
while (1) {
int num_of_tower = 0, num_of_disk = 0;
cout << "Please select the number of towers and disks" << '\n'
<< "tower and disk : ";
cin >> num_of_tower >> num_of_disk;
if (!cin) Invalid_input(num_of_tower, num_of_disk);
else if (num_of_tower < 2)
Invalid_input(num_of_tower, num_of_disk);
}
}
This is just part of the whole code.这只是整个代码的一部分。 I can't call the function,
Invalid_input
, in the else if
statement (for example, after an input of 1 and 3).我不能在
else if
语句中调用 function, Invalid_input
(例如,在输入 1 和 3 之后)。
Excluding this function call, all operations are performed.排除此 function 调用,执行所有操作。 How should I fix it?
我应该如何解决它?
Your Invalid_input
function is being called … but it's not doing anything, This is because, for an input of 1
for num_of_tower
and a valid input for num_of_disk
, there will not be an error on the cin
stream, so the while
loop in your function won't run (because the while (!cin)
test will be false ). Your
Invalid_input
function is being called … but it's not doing anything, This is because, for an input of 1
for num_of_tower
and a valid input for num_of_disk
, there will not be an error on the cin
stream, so the while
loop in your function won '不运行(因为while (!cin)
测试将是false )。
What you should do is to change that while() {...}
loop into a do {... } while();
您应该做的是将
while() {...}
循环更改为do {... } while();
loop, which will always run at least once, even if cin
is not in an error state:循环,它总是至少运行一次,即使
cin
没有出现错误 state:
void Invalid_input(int& num1, int& num2)
{
do {
cout << "You entered an incorrect value!" << '\n';
cin.clear();
cin.ignore(100, '\n');
cout << "Please input again : ";
cin >> num1 >> num2;
} while (!cin);
}
You might also like to add a further check in that function, to ensure that the first input given is at least 2 (as in the main
function):您可能还想在 function 中添加进一步检查,以确保给定的第一个输入至少为 2(如在
main
函数中):
//...
cin >> num1 >> num2;
} while (!cin || num1 < 2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.