Article ID: 132422
Article Last Modified on 6/29/2004
int n = 0;
while (n <= 100) {cin >> n;}
This program is expecting a value greater than 100. If the user inputs
a non-numeric value, the stream's fail bit is set, and the cin object
becomes unusable. All subsequent extractions result in an immediate
return with no value stored. Consequently, the program hangs (stops
responding) in the while loop.
/* No special compile options needed. */
#include <iostream.h>
int ClearError(istream& isIn) // Clears istream object
{
streambuf* sbpThis;
char szTempBuf[20];
int nCount, nRet = isIn.rdstate();
if (nRet) // Any errors?
{
isIn.clear(); // Clear error flags
sbpThis = isIn.rdbuf(); // Get streambuf pointer
nCount = sbpThis->in_avail(); // Number of characters in buffer
while (nCount) // Extract them to szTempBuf
{
if (nCount > 20)
{
sbpThis->sgetn(szTempBuf, 20);
nCount -= 20;
}
else
{
sbpThis->sgetn(szTempBuf, nCount);
nCount = 0;
}
}
}
return nRet;
}
void main()
{
int n = 0, nState;
while (n <= 100)
{
cout << "Please enter an integer greater than 100.\n";
cin >> n;
nState = ClearError(cin); // Clears any errors in cin
}
}
Keywords: kbhowto kbcrt kblangcpp kbcode KB132422