Help

how to secure this program like if user put character in functions then program gives error instead of infinite loop.In short how to put rules and regulation on functions.

#include<iostream>
using namespace std;
int Avg3() //funtion 1 start.
{
int Max_value=3;
int number;
int average=0;
int sum=0;
int x=1;
while(x<=Max_value)
{
cout<<"Enter number\n";
cin>>number;
sum+=number;
x++;
}
average=sum/Max_value;
return average;
} //function 1 end.

int Avg5() //function 2 starts.
{
int Max_value=5;
int number;
int average=0;
int sum=0;
int x=1;
while(x<=Max_value)
{
cout<<"Enter number\n";
cin>>number;
sum+=number;
x++;
}
average=sum/Max_value;
return average;
} //funtion 2 end.

int Avg7() //function 3 starts.
{
int Max_value=7;
int number;
int sum=0;
int average=0;
int x=1;



while(x<=Max_value)
{
cout<<"Enter number\n";
cin>>number;
sum+=number;
x++;
}
average=sum/Max_value;
return average;

} //funcition 3 ends.


int main()
{
int res,res1,res2;
int choice;
char rep;
do{

cout<<"Press 1 for the average of 3 numbers\n";
cout<<"Press 2 for the average of 5 numbers\n";
cout<<"Press 3 for the average of 7 numbers\n";
cin>>choice;
if(choice==1)
{
res=Avg3();
cout<<res<<endl;
}
else if(choice==2)
{
res1=Avg5();
cout<<res1<<endl;
}

else if(choice==3)
{
res2=Avg7();
cout<<res2<<endl;
}

else
{
cout<<"Error! Invalid Selection\n";
}
cout<<"\nDo you want to contineu Y/N\n";


cin>>rep;
}
while(rep== 'y');
}
The only way I know how to do it is read it in as a string and verify the value as a number, then convert it to an INT. May not be as clean as possible but it works.
Last edited on
Rather than just using a raw cin >> directly in the body of your code, you could call a function something like int getnumber(). The code inside the function will do all the validation and error correction. When it receives a valid input, the function returns the value to the calling code.
A very basic example:

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
71
72
#include <iostream>
#include <cctype>

using namespace std;

int getInteger()
{
    int n;
    
    while (!(cin >> n))
    {
        cin.clear();            // not valid, clear status flags
        cin.ignore(1000, '\n'); // discard rest of line
    }
    
    return n;
}

char getYN()
{
    char ch;
    do {
        cin >> ch;
        ch = tolower(ch);
    } while ( ch != 'y' && ch != 'n');
    
    return ch;
}

int Avg3()
{
    int Max_value=3;
    int number;
    int average=0;
    int sum=0;
    int x=1;
    
    while(x<=Max_value)
    {
        cout<<"Enter number\n";
        number = getInteger();
        sum+=number;
        x++;
    }
    average=sum/Max_value;
    return average;
}      


int main()
{   
    do {
        cout << "Press 1 for the average of 3 numbers\n"
                "Press 2 for the average of 5 numbers\n"
                "Press 3 for the average of 7 numbers\n";
                
        int choice = getInteger();
        
        if (choice == 1)
        {
            int res = Avg3();
            cout << res << endl;
        }        
        else
        {
            cout<<"Error! Invalid Selection\n";
        }
        
        cout << "\nDo you want to continue Y/N\n";
        
    } while ( getYN() == 'y');
}

Last edited on
Thanks problem solved!
Derscription of this function:
1
2
3
4
5
6
7
8
9
10
11
12
int getInteger()
{
    int n;
    
    while (!(cin >> n))
    {
        cin.clear();            // not valid, clear status flags
        cin.ignore(1000, '\n'); // discard rest of line
    }
    
    return n;
}


We could write the code like this:
1
2
3
4
5
6
7
8
    int n;            // declare an integer
    
    cin >> n;         // attempt to get an integer from cin

    if ( cin.fail() ) // test the status of cin to see if it failed
    {
                      // action to be taken if the input failed.
    }


In the original code,
 
    while (!(cin >> n))

this line first attempts to read an integer, then checks the status of cin. If the input failed, the condition will be true and the body of the loop will be executed.

The rest of the code is taken in order to clear up the mess.

First, the fail() flag was set. We need to reset (clear) the flag before we are able to use cin again. That is what cin.clear(); does.

Now we are able to use cin. But we know the previous input caused a failure, there is some invalid input. That input remains in the input buffer. It needs to be removed. Since we don't know for sure what was typed, all we can do is to ignore the input until the end of the line.

cin.ignore() on its own will read and discard a single character.
cin.ignore(1000, '\n'); will ignore up to 1000 characters, or until the newline character '\n' is found.

Last edited on
Topic archived. No new replies allowed.