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
#include<iostream>
#include<array>
usingnamespace 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]);
}
#include "stdafx.h"
#include<iostream>
#include<array>
usingnamespace 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]);
}
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