I have a validation loop that's supposed to check that a string is an integer, and it works the first time I run through the bigger sentinel loop, but in each iteration after it prints the error message first before reprompting the user. The prompt still works after, but how do I get rid of that first error message? If I need to post the actual sentinel loop please let me know. Thanks for any help!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string num;
//prompt for # of times
cout << "Number of times: ";
cin.clear();
getline(cin,num);
//test for valid number
while (!isdigit(num[0])) {
cout << "pwease don't try to break my app..." << endl << endl;
cin.clear();
//update loop
cout << "Number of times: ";
getline(cin,num);
}
System("cls") is one way but you can look up other ways to clear the screen. Basically that's what you need to do. Otherwise if you want only that particular point to be erased then you need to find a way to set the console cursor position (I know this can be done on windows).
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
template<typename T> T getVal( string prompt )
{
T value;
string line, remainder;
while( true )
{
cout << prompt;
getline( cin, line );
stringstream ss( line );
if ( ss >> value && !( ss >> remainder ) ) return value; // If valid item and NOTHING ELSE
cout << "Invalid input\n";
}
}
int main()
{
int i = getVal<int> ( "\nEnter an integer: " ); cout << "Valid integer is " << i << '\n';
double d = getVal<double>( "\nEnter a double: " ); cout << "Valid double is " << d << '\n';
char c = getVal<char> ( "\nEnter a char: " ); cout << "Valid char is " << c << '\n';
}
Enter an integer: 3A
Invalid input
Enter an integer: 30 40 50
Invalid input
Enter an integer: 30
Valid integer is 30
Enter a double: 12.5A
Invalid input
Enter a double: 12.5e2
Valid double is 1250
Enter a char: abc
Invalid input
Enter a char: a
Valid char is a