Why Input Data type conflict is causing infinite loop

The code below shows a simple program, which is a small piece of code from simple math game.But in the add() function...if we cin a data type other than an int..the console displays Try again endlessly without moving to next line and not letting me cin again.Now I might have fixed this using any tool,debugger etc. but I want to learn the root cause of this problem, because even if it is memory overflow it shouldn't cause this specific problem.Detailed answer appreciated

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

#include<iostream>
#include<array>
using namespace std;

array <int,3> calc;

/* calc[0] is for first number, [1] for second number ,[2] is for storing user's input */

//This function evaluates Addition of two numbers
void add(int a,int b)
{

    calc[2]=0;
    cout<<"What is "<<a<<"+"<<b<<endl;
    cin>>calc[2];

    while(true)
    {
        if(calc[2]==(a+b))
        {
            cout<<calc[2]<<" is the right answer"<<endl<<endl<<endl;
            break;
        }

        else
        {
            cout<<"Try again"<<endl;
            cin>>calc[2];
            continue;
        }
    }
}

int main()
{


    calc[0]=30,calc[1]=20;
    add(calc[0],calc[1]);

}
Last edited on
http://stackoverflow.com/questions/18400620/cin-for-an-int-inputing-a-char-causes-loop-that-is-supposed-to-check-input-to-go
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
#include "stdafx.h"
#include<iostream>
#include<array>
using namespace std;

array <int,3> calc;

/* calc[0] is for first number, [1] for second number ,[2] is for storing user's input */

//This function evaluates Addition of two numbers
void add(int a,int b)
{
    calc[2]=0;
    cout<<"What is "<<a<<"+"<<b<<endl;
    cin>>calc[2];

    while(true)
    {
        if(calc[2]==(a+b))
        {
            cout<<calc[2]<<" is the right answer"<<endl<<endl<<endl;
            break;
        }
        else
        {
			cin.clear(); // clears the error flags
			// this line discards all the input waiting in the stream
			cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            cout<<"Try again"<<endl;
            cin>>calc[2];
           
        }
    }
}

int main()
{


    calc[0]=30,calc[1]=20;
    add(calc[0],calc[1]);

}
Formatted input. See http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

It basically says:
1. IF either no characters were extracted, or the characters extracted could not be interpreted as a valid value of the appropriate type (int) THEN set failbit
2. IF failbit is already set, THEN fail automatically
Topic archived. No new replies allowed.