Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong Inputs will cause the program to exit

Tags:

c++

Look at this code:

#include <iostream>
using namespace std;
int main()
{
    string s;
    int n;
    float x;
again:
    cout << "Please Type this: ABC456 7.8 9 XYZ\n";
    cin >> s >> n >> x >> s;
    cout << "\nDo you want to try Again(y/n)? ";
    char t;
    cin >> t;
    if (t=='y' || t=='Y')
        goto again;
    return 0;
}

Just try to type "ABC456 7.8 9 XYZ" and press enter, it will cause the program exit before prompting the user to try again. I know the inputs are wrong and they are not in their types, but why it causes the exit? and how to avoid such exit?

like image 396
Inside Man Avatar asked Apr 30 '12 06:04

Inside Man


1 Answers

Change

cin >> s >> n >> x >> s;

to

cin >> s >> x >> n >> s;

As you are entering 7.8 as 2nd input but you are collecting it in a integer variable instead of a floating point variable. As a result of this when you enter:

ABC456 7.8 9 XYZ

s gets ABC456, n gets 7 (as it is of int type and the input buffer still has .8 9 XYZ\n in it). Next n gets .8 and finally s gets "9". Now the input buffer has XYZ\n in it. The next time when you read the input into t to get the user's choice, X gets read into t and since it is not y or Y, the loop exits.

like image 190
codaddict Avatar answered Nov 14 '22 20:11

codaddict