【发布时间】:2014-02-08 17:47:14
【问题描述】:
在我的简单Fraction 类中,我有以下方法来获取numerator 的用户输入,该方法适用于检查garbage 之类的垃圾输入,但无法识别以整数开头的用户输入,然后是垃圾,1 garbage 或 1garbage。
void Fraction::inputNumerator()
{
int inputNumerator;
// loop forever until the code hits a BREAK
while (true) {
std::cout << "Enter the numerator: ";
// attempt to get the int value from standard input
std::cin >> inputNumerator;
// check to see if the input stream read the input as a number
if (std::cin.good()) {
numerator = inputNumerator;
break;
} else {
// the input couldn't successfully be turned into a number, so the
// characters that were in the buffer that couldn't convert are
// still sitting there unprocessed. We can read them as a string
// and look for the "quit"
// clear the error status of the standard input so we can read
std::cin.clear();
std::string str;
std::cin >> str;
// Break out of the loop if we see the string 'quit'
if (str == "quit") {
std::cout << "Goodbye!" << std::endl;
exit(EXIT_SUCCESS);
}
// some other non-number string. give error followed by newline
std::cout << "Invalid input (type 'quit' to exit)" << std::endl;
}
}
}
我看到了一些关于为此使用getline 方法的帖子,但是当我尝试它们时它们没有编译,并且我无法找到原始帖子,抱歉。
【问题讨论】:
标签: c++ error-handling user-input cin