在我的简单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
方法的帖子,但是当我尝试它们时它们没有编译,而且我很难找到原帖,抱歉。
答案 0 :(得分:1)
更好地检查如下:
// attempt to get the int value from standard input
if(std::cin >> inputNumerator)
{
numerator = inputNumerator;
break;
} else { // ...
或者是:按照建议解析合适std::getline()
和std::istringstream
的完整输入行。