【发布时间】:2015-05-23 08:44:06
【问题描述】:
我是编程新手,在验证以下 C++ 程序的输入时遇到了一些问题。
我的目标是防止用户在给定域 [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;
}
【问题讨论】:
标签: c++ validation debugging input while-loop