jeudi 19 mars 2015

C++ Debugging – Input Validation requires input twice


I'm new to programming, and I've been having some trouble with input validation for the following C++ program.


My objective is to prevent the user from inputting anything other than an integer within the given domain [100,999].


The program seems to pause after the first number is entered. The user must enter in a second value before the code cout << "you entered " << number << endl; is executed. The first input is not even considered.


The problem seems to stem from the while loop. Part of it was taken from another online forum, so I'm entirely sure how it works. But I do know this, without the loop, the program executes after the first input rather than pausing (without the benefit of input validation, of course).


How can I prevent the user from having to input their number twice?



#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;
}



Aucun commentaire:

Enregistrer un commentaire