Help with my program

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.

From,
http://www.dreamincode.net/forums/topic/83273-numbers-only-no-letters-validation/

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*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>
 
using namespace 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' ) return false;
    // else if reach here ...
    return true;
}
     
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();
}

Im not sure but have you tried a bool whit numeric limits?

something like

bool = name_of_your_bool

and put
1
2
3
4
5
6
7
8
9
10
11
12

do {
 cout << "HOW MANY BOTTLES IN THE BASKET? ";
cin >> bottles;
                        name_of_your_bool = cin.fail();
			cin.clear();
			cin.ignore(numeric_limits < streamsize>::max(), '\n');



			} while (boolname == true);
Last edited on
Topic archived. No new replies allowed.