简体   繁体   中英

cin.ignore() and cin.clear() in C++

So I understand that a piece of code:

cin.ignore(80, '\n');

will clear the buffer of up to 80 characters until it hits a return (Enter key) and stop... right?

Here are the questions...

1) What is different about simply doing cin.ignore(); with no parameters? Which is better used in what situation?

2) cin.clear(); says it clears error flags... what does this mean? What are error flags and why do you want them cleared?

Thanks!

Error flags are set on a stream object whenever some operation on it fails. Once the stream is in error, no further operations can succeed on it until you reset the error state.

Here's a simple example:

std::istringstream iss("ABC123");

int n;
iss >> n;

assert(!iss);

Now the stream is in error. However, there's still data in it, and it might be worthwhile resetting and trying again:

iss.clear();  // note: this must come first!

std::string token;
iss >> token;

assert(iss);

Instead of another extraction, you could also call iss.ignore() after the clear() , in case you know what you have to ignore before it makes sense to try again.

Usually, this sort of trial-and-error isn't a very good approach, I find. I would always use getline on the stream first to get complete lines. This can only fail when the stream has been exhausted (end of file, or end of string). Then you can proceed to process each line by a dedicated parsing logic, and errors can be handled in the most appropriate way. The error flags on the original stream are too crude to allow for elegant control flow design.

I can answer your second question . The cin.clear() function is useful when you trying to enter two different paragraphs. For example :

std::vector<std::string> veca,vecb;
std::string x;
while(getline(std::cin,x))
     veca.push_back(x);
cin.clear();
while(getline(std::cin,x))
     vecb.push_back(x);

if you didn't use the cin.clear() function , the vecb got nothing, because the cin met an end-of-file before. Hope this could help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM