2014-02-08 31 views
2

在我的簡單Fraction類中,我有以下方法獲取numerator的用戶輸入,它可以很好地檢查諸如garbage之類的垃圾輸入,但無法識別以整數開頭的用戶輸入,然後是垃圾,1 garbage1garbage用戶輸入的整數後跟垃圾

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方法對於這一點,但是當我嘗試過,他們沒有編制,而且我無法找到原來的職位,對不起。

回答

1

最好檢查如下:

// attempt to get the int value from standard input 
if(std::cin >> inputNumerator) 
{ 
    numerator = inputNumerator; 
    break; 
} else { // ... 

或者是:按照建議,以解析一個完整的輸入線適當地結合std::getline()std::istringstream

+0

嗯......解決了所有問題 – michaelsnowden

+0

@doctordoder Bwoooah!這在我的第一槍快,真的? –

+0

是啊,到目前爲止好大聲笑 – michaelsnowden