Validating user input
Jan 12, 2014 at 9:19pm UTC
Hello, I am in the process of learning about validating input so that when the user types in a word instead of an integer, the program doesn't crash. This is a small piece of code that will validate the scenario mentioned above but with one problem. Whenever I actually type in a valid number ex: 123, directly after starting the program, I will have to type it twice for the function to accept it. Does anyone know why this is?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
using namespace std;
int validate(int );
int main()
{
int integer;
cout << "enter a number\n" ;
cin >> integer;
integer = validate(integer);
}
int validate(int number)
{
bool failed;
do
{
cin.clear();
if (cin >> number && number > 0)
{
cout << "value entered: " << number << endl;
failed = false ;
}
else
{
failed = true ;
cout << "You must enter a positive integer." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n' );
}
cout << endl;
} while (failed == true || number <= 0);
return number;
}
Jan 12, 2014 at 9:36pm UTC
Because you're asking for input twice.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
using namespace std;
int validate(int );
int main()
{
int integer;
cout << "enter a number\n" ;
cin >> integer; // <---- Once here.
integer = validate(integer);
}
int validate(int number)
{
bool failed;
do
{
cin.clear();
if (cin >> number && number > 0) // <---- And once here
{
cout << "value entered: " << number << endl;
failed = false ;
}
else
{
failed = true ;
cout << "You must enter a positive integer." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n' );
}
cout << endl;
} while (failed == true || number <= 0);
return number;
}
Jan 12, 2014 at 11:39pm UTC
lol wow, can't believe I didn't catch that, Thanks!
Topic archived. No new replies allowed.