Using cin >> to error handle

梦想与她 提交于 2021-02-08 09:16:40

问题


I came across this in my readings...

while(!(std::cin >> array[i])) 
{
std::cin.clear(); 
while(std::cin.get()!= '\n') 
continue; 
std::cout << "enter a new input: ";
}

And, I don't really understand how the error handling is working. std::cin.clear() is used but the code continues to get characters from the cin object in the next line and then uses a continue statement. What exactly does the clear do if it doesn't clear the cin? Thank you.


回答1:


what cin.clear() does is to clear the cin stream's error flags.When it does this cin stream operations can continue.the next line extracts a character from the stream and returns it. To understand what the loop does consider the following case :

Suppose the array is of type int and you enter:abc and then press enter. cin identifies that the string input cannot go into the int array. and so it returns false and sets the error flags.when you perform cin.clear() it resets the error flags so that further operartions can continue(cin.get() can work).Now cin.get() extracts a from the stream. since it is not equal to '\n' the loop continues(second loop) until it extracts '\n' => meaning the wrong i/p you just entered is all washed away u can start afresh




回答2:


.clear() clears the error flags in cin. They get set if the input couldn't be converted for example. While any error flag is set, extracting input from cin will silently fail.




回答3:


The clear function sets a new value for the error control state.

Consider the following example:

// clearing errors
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  char buffer [80];
  fstream myfile;

  myfile.open ("test.txt",fstream::in);

  myfile << "test";
  if (myfile.fail())
  {
    cout << "Error writing to test.txt\n";
    myfile.clear();
  }

  myfile.getline (buffer,80);
  cout << buffer << " successfully read from file.\n";

  return 0;
}

In the above example myfile is opened for input operations, but only an output operation is performed on it, so failbit is set. The example then calls clear in order to remove the flag and allow further operations like getline to be successfully performed on myfile.

Reference: ios::clear




回答4:


while(!(std::cin >> array[i])) 
{
std::cin.clear();             //clears any error flags on cin so get() works
while(std::cin.get()!= '\n')  //in case white space is in the stream
{                             //loop until the end of line character
   continue;              
}
std::cout << "enter a new input: ";
}

Info in the comments.



来源:https://stackoverflow.com/questions/6408117/using-cin-to-error-handle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!