我尝试提示用户输入并进行验证。 例如,我的程序必须接受3个用户输入。 一旦命中非整数,就会打印错误信息并提示再次输入。 下面是我的程序运行时的样子:
输入编号:a
输入错误
输入编号:1
输入编号:b
输入错误
输入编号:2
输入编号:3
输入的数字为1,2,3
下面是我的代码:
double read_input()
{
double input;
bool valid = true;
cout << "Enter number: " ;
while(valid){
cin >> input;
if(cin.fail())
{
valid = false;
}
}
return input;
}
我的主要方法:
int main()
{
double x = read_input();
double y = read_input();
double z = read_input();
}
当我的第一个输入是非整数时,程序就会自己退出。 它不会再次要求提示。 我怎么能修好它呢? 或者我应该使用一个do while循环,因为我要求用户输入。
提前谢谢你。
当读取失败时,您将valid
设置为false
,因此while
循环中的条件为false
,程序返回input
(顺便提一下,它没有初始化)。
您还必须在再次使用缓冲区之前清空它,类似于:
#include <iostream>
#include <limits>
using namespace std;
double read_input()
{
double input = -1;
bool valid= false;
do
{
cout << "Enter a number: " << flush;
cin >> input;
if (cin.good())
{
//everything went well, we'll get out of the loop and return the value
valid = true;
}
else
{
//something went wrong, we reset the buffer's state to good
cin.clear();
//and empty it
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid input; please re-enter." << endl;
}
} while (!valid);
return (input);
}
你的问题确实让我陷入了其他问题,比如在失败时清除cin()--
double read_input()
{
double input;
int count = 0;
bool valid = true;
while(count != 3) {
cout << "Enter number: " ;
//cin.ignore();
cin >> input;
if(cin.fail())
{
cout << "Wrong Input" <<endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else
count++;
}
return input;
}
问题在while条件下
bool valid = true;
while(valid){
你循环直到你得到一个无效的输入,这绝对不是你想要的! 循环条件应该是这样的
bool valid = false;
while(! valid){ // repeat as long as the input is not valid
以下是read_double
的修改版本
double read_input()
{
double input;
bool valid = false;
while(! valid){ // repeat as long as the input is not valid
cout << "Enter number: " ;
cin >> input;
if(cin.fail())
{
cout << "Wrong input" << endl;
// clear error flags
cin.clear();
// Wrong input remains on the stream, so you need to get rid of it
cin.ignore(INT_MAX, '\n');
}
else
{
valid = true;
}
}
return input;
}
例如,在你的主体中,你需要要求尽可能多的双份工作
int main()
{
double d1 = read_input();
double d2 = read_input();
double d3 = read_input();
cout << "Numbers entered are: " << d1 << ", " << d2 << ", " << d3 << endl;
return 0;
}
您可能还希望有一个循环,在该循环中调用read_double()
并将返回的值保存在数组中。