i wrote a simple program, which asks the user to enter a number other than -1. if the user enters that number , it will ask him to enter an another number and store it into a dynamic array. the problem is that when the user enters some letters instead an int, the while loop runs infinitely. i cannot figure out why because i thought i have
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.clear();
which takes care if the streaming goes bad.
# include <iostream>
usingnamespace std;
int main()
{
unsigned size = 2;
int * ptr = newint[size];
int input;
cin >> input;
int i = 0;
while (input != -1)
{
cout << "enter a number" << endl;
cin >> ptr[i];
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.clear();
//cin.getline( )
++i;
cout << "enter -1 to exit loop or any number to continue ";
cin >> input;
}
// should be j< i to take out garbage value
for (unsigned j = 0; j <= i; ++j)
cout << "ptr[j] = " << ptr[j] << "\n";
cout << endl;
system("pause");
}
The problem is that cin.clear(); appears aftercin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');. It seems that this causes undefined behavior. So move line 15 before line 14.
OP: coder777 has already given you a working solution, why don't you undertake the little extra effort of googling the unfamiliar and come back with specific questions instead of wanting to be spoon-fed?
gunnerfunner: i don't really appreciate what you just said nor does it help by any means. coder777 posted the solution , but i can still ask him for the reasoning . it is not called spoonfeeding but digging deeper.
how about u post some links with the explanation . that would really help. then we can talk again.
cin.clear() helps in clearing the error flags which are set when std::cin fails to interpret the input.
cin.ignore(), on the other hand helps in removing the input contents that could caused the read failure. cin.ignore(), by default only clears one character (the first one). cin.ignore(1000) would mean the next 1000 characters in the read buffer shall be ignored. cin.ignore(1000,'\n') would mean either next 1000 characters or the characters until '\n' shall be ignored, whichever comes first.
Since ignore() is called before clear() it does not remove the invalid input. Hence the other cin will fail and ignore() will not have any effect whatsoever.