在我的简单 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
的帖子方法,但是当我尝试它们时它们没有编译,而且我找不到原始帖子,抱歉。
最佳答案
最好按如下方式检查:
// attempt to get the int value from standard input
if(std::cin >> inputNumerator)
{
numerator = inputNumerator;
break;
} else { // ...
或者是:按照建议解析一个完整的输入行,适本地组合 std::getline()
和 std::istringstream
。
关于c++ - 用户输入整数后跟垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21649543/