I just created a cgpa calculator. I was able to stop infinite loop when a letter is being input instead of integer but i don't know how to stop a user from entering a letter. How do i create something like an erro message that says "please input the correct value". Pls help me. Thanks.
/*I have some basic code:
cout << "HOW MANY BOTTLES IN THE BASKET? ";
cin >>bottles;
I want to put an if statement
to make sure that no letters are entered
and only numbers are?
*/
#include <iostream>
#include <string>
#include <cstdlib>
usingnamespace std;
void cinFlush()
{
while( cin.get() != '\n' );
}
bool isInteger( string s )
{
for( unsigned i=0; i<s.length(); ++ i )
if( s[i] < '0' || s[i] > '9' ) returnfalse;
// else if reach here ...
returntrue;
}
int main()
{
int bottles;
// method 1.
for(;;)/> // forever loop ... until break ...
{
cout << "HOW MANY BOTTLES IN THE BASKET? ";
cin >> bottles;
if( !cin.good() )
{
cout << "Enter integers only ...\n";
cin.clear();
cinFlush();
continue; // right now from the top of the forever loop ...
}
// if reach hear ...
cinFlush();
break;
}
cout << "You entered " << bottles << endl;
// method 2.
string bottlesStr;
for(;;)/> // forever loop ... until break ..
{
cout << "HOW MANY BOTTLES IN THE BASKET? ";
getline(cin, bottlesStr);
if( !isInteger( bottlesStr ) )
{
cout << "Enter integers only ...\n";
continue; // right now from the top of the forever loop ...
}
// if reach hear ...
bottles = atoi( bottlesStr.c_str() );
break;
}
cout << "You entered " << bottles
<< "\n\nPress 'Enter' to continue ... " << flush;
cinFlush();
}