我试图提示用户输入并进行验证.例如,我的程序必须输入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;
}
Run Code Online (Sandbox Code Playgroud)
我的主要方法:
int main()
{
double x = read_input();
double y = read_input();
double z = read_input();
}
Run Code Online (Sandbox Code Playgroud)
当我的第一个输入是非整数时,程序就会自行退出.它不再要求提示.我怎么能修好它?或者我应该使用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);
}
Run Code Online (Sandbox Code Playgroud)