How to clear unnecessary input stream in C ++

I would like the user to enter a central number of characters, e.g. 10, however, the user can enter more than 10.

for(int i = 0 ; i< 10 ; i++) cin>>x; 

An extra character may cause my code to crash, as I ask you to enter it later.

How can I clear the input at this moment when the user enters more than 10?

Many thanks!

+4
source share
4 answers

By the way, to avoid duplicating all of this code every time, I once wrote a small template function to do this job:

 template<typename InType> void AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString, InType & Result) { do { Os<<Prompt.c_str(); if(Is.fail()) { Is.clear(); Is.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } Is>>Result; if(Is.fail()) Os<<FailString.c_str(); } while(Is.fail()); } template<typename InType> InType AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString) { InType temp; AcquireInput(Os,Is,Prompt,FailString,temp); return temp; } 

The first overload may be preferable if you want to avoid copying, the second may be more convenient for built-in types. Examples of using:

 //1st overload int AnInteger; AcquireInput(cout,cin,"Please insert an integer: ","Invalid value.\n",AnInteger); //2nd overload (more convenient, in this case) int AnInteger=AcquireInput(cout,cin, "Please insert an integer: ","Invalid value.\n"); 
0
source
  std::cin.clear(); std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n'); 

This should reset failbit and ignore bad input.

+5
source

cin goes into error mode and stops doing anything if the user enters an invalid input. You need to add an invalid input check and loop to repeat.

 for(int i = 0 ; i< 10 ; i++) while ( ( cin >> x ).rdstate() == ios::failbit ) { cin.clear(); cin.ignore( numeric_traits<streamsize>::max(), '\n' ); } 

This is a lot of work, but you need to define some kind of policy to ignore invalid input. There are other options; it just ignores the rest of the line.

0
source

This shows how to clear the entire buffer from an error.

from: http://support.microsoft.com/kb/132422

 /* 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 } } 
0
source

Source: https://habr.com/ru/post/1301177/


All Articles