Is there a quick and easy way to validate or not allow a user to input anythign other than an int?
example:
1 2 3 4 5 6 7
cout << "Enter your 3 test scores and I will average them: ";
cin >> score1;
cin >> score2;
cin >> score3;
if (score1 < 0 || score2 < 0 || score3 < 0 ) //tests if scores are positive
cout << "Invalid input, score cannot be less than zero.\n";
//need to find a way to loop if user input anything other than integer.
#include <iostream>
#include <sstream>
int get_int(int min, std::string prompt)
{
int ret_integer;
std::string str_number;
while(true) {
std::cout << prompt;
std::getline(std::cin, str_number); //get string input
std::stringstream convert(str_number); //turns the string into a stream
//checks for complete conversion to integer and checks for minimum value
if(convert >> ret_integer && !(convert >> str_number) && ret_integer >= min) return ret_integer;
std::cin.clear(); //just in case an error occurs with cin (eof(), etc)
std::cerr << "Input must be >= " << min << ". Please try again.\n";
}
}
int main()
{
constint min_score=1; //example
std::cout << "Enter your 3 test scores and I will average them.\n";
int score1=get_int(min_score,"\nPlease enter test score #1: ");
int score2=get_int(min_score,"\nPlease enter test score #2: ");
int score3=get_int(min_score,"\nPlease enter test score #3: ");
//the rest of your code
return 0;
}
Thanks, ill need to think on this of what your doing, not familiar with std:: method but i guess i understand it. I just need to understand functions and how they work a little better. But it should work.
Here is a clean readable solution to make sure the user has entered an int.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int num; //variable to store the number entered by the user.
//Prompt the user to enter an integer.
cout << "Enter an integer: ";
cin >> num;
//While the input entered is not an integer, prompt the user to enter an integer.
while(!cin)
{
cout << "That was no integer! Please enter an integer: ";
cin.clear();
cin.ignore();
cin >> num;
}
//Print the integer entered by the user to the screen.
cout << "The integer entered is " << num << endl;
The solutions given so far make assumptions about the input. The user could input "10abc" and the input will be accepted (as the integer '10') and leave the (presumed) garbage in the input.