Error handling in C++ -
how make cin statement accepts integers?
i don't think can force std::cin
refuse accept non-integral input in cases. can write:
std::string s; std::cin >> s;
since string doesn't care format of input. however, if want test whether reading integer succeeded can use fail()
method:
int i; std::cin >> i; if (std::cin.fail()) { std::cerr << "input not integer!\n"; }
alternatively, can test cin
object itself, equivalent.
int i; if (std::cin >> i) { // use input } else { std::cerr << "input not integer!\n"; }
Comments
Post a Comment