输入验证需要输入两次
Input validation requires input twice
我是编程新手,我在以下 C++ 程序的输入验证方面遇到了一些问题。
我的 objective 是为了防止用户在给定域 [100,999] 中输入整数以外的任何内容。
程序似乎在输入第一个数字后暂停。在执行代码 cout << "you entered " << number << endl;
之前,用户必须输入第二个值。甚至不考虑第一个输入。
问题似乎源于 while 循环。它的一部分来自另一个在线论坛,所以我完全确定它是如何工作的。但我确实知道这一点,如果没有循环,程序会在第一次输入后执行而不是暂停(当然没有输入验证的好处)。
我怎样才能避免用户必须输入他们的号码两次?
#include <iostream>
#include <iomanip>
#include <math.h>
#include <limits>
using namespace std;
int main() {
int number = 0;
cout << "Please enter a whole number from 100 to 999:\n\n";
cin >> number;
//Check to see if entered value is a character
//or integer is within the given range
while ((cin >> number).fail() || cin.peek() != '\n' || number > 999 || number < 100)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please enter an integer from 100 to 999:\n";
}
cout << "you entered " << number << endl;
char q;
cin >> q;
return 0;
}
您正在使用 (cin >>number).fail()
,它再次调用 cin>>
。把第一个cin
去掉就好了
我是编程新手,我在以下 C++ 程序的输入验证方面遇到了一些问题。
我的 objective 是为了防止用户在给定域 [100,999] 中输入整数以外的任何内容。
程序似乎在输入第一个数字后暂停。在执行代码 cout << "you entered " << number << endl;
之前,用户必须输入第二个值。甚至不考虑第一个输入。
问题似乎源于 while 循环。它的一部分来自另一个在线论坛,所以我完全确定它是如何工作的。但我确实知道这一点,如果没有循环,程序会在第一次输入后执行而不是暂停(当然没有输入验证的好处)。
我怎样才能避免用户必须输入他们的号码两次?
#include <iostream>
#include <iomanip>
#include <math.h>
#include <limits>
using namespace std;
int main() {
int number = 0;
cout << "Please enter a whole number from 100 to 999:\n\n";
cin >> number;
//Check to see if entered value is a character
//or integer is within the given range
while ((cin >> number).fail() || cin.peek() != '\n' || number > 999 || number < 100)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please enter an integer from 100 to 999:\n";
}
cout << "you entered " << number << endl;
char q;
cin >> q;
return 0;
}
您正在使用 (cin >>number).fail()
,它再次调用 cin>>
。把第一个cin
去掉就好了