cin.ignore(3) after failure to get a double with cin >> var
I'm learning c++ with c++ Primer Plus, and I'm on chapter 7 and trying to create the following function:
开发者_开发百科double getDouble(const char * message){
double temp;
std::cout << (message);
if (!(std::cin >> temp)){
std::cin.clear();
std::cin.ignore(3); // Why does this work specifically?
std::cout << "Input not double!" << std::endl;
return 0.0;
}
return temp;
}
istream::ignore
well, ignores the next N characters or until the delimiter is hit. The 3
seems like a random magic number to me. Or what did you want to know?
The C++ standard guarantees (§27.6.1.3/23 in the '03 standard) that passing std::numeric_limits<std::streamsize>::max()
will ignore everything in the stream until the specified delimiter or end of input is reached. So change
std::cin.ignore(3);
to
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
Using magic numbers such as 3
when calling ignore
is very rarely appropriate.
精彩评论