2
在我的簡單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
方法對於這一點,但是當我嘗試過,他們沒有編制,而且我無法找到原來的職位,對不起。
嗯......解決了所有問題 – michaelsnowden
@doctordoder Bwoooah!這在我的第一槍快,真的? –
是啊,到目前爲止好大聲笑 – michaelsnowden