输入有效的输入值后仍有提示

Still being prompted after entering a valid input value

本文关键字:输入 提示 有效      更新时间:2023-10-16

我这样做是为了分配,但即使我输入了所需范围内的有效输入,我仍然会收到提示。这两个输入提示都会发生这种情况。我怀疑问题出在setupGame函数的while块中。

#include <iostream>  
using namespace std;
bool setupGame(int numberRef, int triesRef);

int main(){
cout<<"hello world";
setupGame(4,4);
cout<<"enough";
}

//SETUP GAME FUNCTION
bool setupGame(int numberRef, int triesRef) { 
do { 
cout << "ENTER A NUMBER BETWEEN 1 and 100" << endl; 
cin >> numberRef;
cin.clear(); 
//your code here 
cout << "You entered: " << numberRef << endl; 
if (numberRef==-1) { 
cout << "You do not want to set a number " << endl; 
cout << "so you stopped the program" << endl;  
} 

else if(numberRef >=1 && numberRef <=100) 
do { 
cout << "ENTER TRIES BETWEEN 3 and 7" << endl; 
cin >> triesRef;
cin.clear();
//cin.ignore( 'n');   
cout<< "You entered: "<< triesRef<< endl; 
if (triesRef==-1) { 
cout << "You do not want to set tries. "; 
cout << "so you stopped the program" << endl;
} else if(triesRef <= 3 && triesRef >= 7){
cout<<"Number of tries should be between 3 and 7";
}
} 
while(numberRef >=1 && numberRef <=100);{ 
return true; 
}
} 
while(triesRef >= 3 && triesRef <= 7);{
return true;
} }

您正与这些嵌套循环纠缠在一起。您的提示不断打印,因为while循环:

while(numberRef >=1 && numberRef <=100)

将继续重复它的前一个do块,直到您输入一个小于1或大于100的值,最后的while循环也是如此。

我假设您使用cin.clear()来刷新以前的输入,如果您停止它,那就不是cin.clear()的目的。相反,它用于清除cin的错误状态。请在这里仔细阅读。

下面是实现您想要的代码,请观察我是如何在每次cin提示后实现while循环以确保输入有效字符的。

#include <iostream> 
#include <fstream> 
using namespace std;
bool setupGame(int numberRef, int triesRef);
int main(){
cout<<"hello world";
setupGame(4,4);
cout<<"enough";
}
//SETUP GAME FUNCTION
bool setupGame(int numberRef, int triesRef) { 
cout << "ENTER A NUMBER BETWEEN 1 and 100" << endl; 
cin >> numberRef;
while((numberRef < 1 || numberRef > 100 || cin.fail()) && numberRef != -1) {
cin.clear(); // Used to clear error state of cin
cin.ignore(); // Might want to ignore the whole line
cout<<"Number should be between 1 and 100, or -1 , please try again: ";
cin>>numberRef;
}  
cout << "You entered: " << numberRef << endl; 
if (numberRef==-1) { 
cout << "You do not want to set a number " << endl; 
cout << "so you stopped the program" << endl;  
}
if(numberRef >=1 && numberRef <=100) {
cout << "ENTER TRIES BETWEEN 3 and 7" << endl; 
cin >> triesRef; 
while(triesRef < 3 || triesRef > 7 || cin.fail()) {
cin.clear(); // Used to clear error state of cin
cin.ignore(); // Might want to ignore the whole line
cout<<"Tries should be between 3 and 7 , please try again: ";
cin>>triesRef;
} 
cout<< "You entered: "<< triesRef<< endl;
if (triesRef==-1) { 
cout << "You do not want to set tries. "; 
cout << "so you stopped the program" << endl;
return false;
} 
}
}