2013-03-18 109 views
0

我剛開始用C++(從Java來),我試圖做一些基本的練習。這個想法是要求除5以外的任何輸入,如果用戶輸入5,顯示消息,並且如果用戶輸入10次以外的任何其他信息,則顯示另一個消息。這裏的代碼:C++輸入不被讀取

void notFive() { 
    int count = 0; 
    while (count < 10) { 
     int input = 0; 
     cout << "Enter any number other than 5." << endl; 
     cin >> input; 
     if (input == 5) 
      break; 
     count++; 
    } 
    if (count == 10) 
     cout<<"You are more patient than I am, you win."; 
    else 
     cout << "You weren't supposed to enter 5!"; 
} 
} 

我的問題是,所有這些代碼是打印出「輸入除5以外的任何數字」。 10次​​,然後說「你對我更有耐心,你贏了。」任何想法有什麼不對?

,如果你們希望我所有的代碼(以確保我不只是作爲一個白癡),那就是:

#include <iostream> 
#include <stdio.h> 
using namespace std; 

class Hello { 

public: 
    void notFive() { 
     int count = 0; 
     while (count < 10) { 
     int input = 0; 
     cout << "Enter any number other than 5." << endl; 
     if (! (cin >> input)) { 
      cout << "std::cin is in a bad state! Aborting!" << endl; 
      return; 
} 
     if (input == 5) 
      break; 
     count++; 
     } 
     if (count == 10) 
      cout<<"You are more patient than I am, you win."; 
     else 
      cout << "You weren't supposed to enter 5!"; 
    } 
}hello; 

int main() { 
    Hello h; 
    h.notFive(); 
    return 0; 
} 
+2

你今天做之前,任何其他輸入?如果'cin'處於不良狀態,它將不會嘗試執行更多輸入。 – 2013-03-18 19:11:38

+0

根據猜測,標準輸入未連接到交互式終端對等設備。您使用什麼操作系統? – antlersoft 2013-03-18 19:12:20

+0

當你使用調試器時,哪一行失敗? – 2013-03-18 19:12:27

回答

0

這裏是我的意見:

  1. fflush(stdin)無效。 stdin不能被刷新。另外, 這可能與cin的輸入不同。
  2. 您需要cin >> input後檢查cin.fail。如果我輸入一個 字母,您的輸入語句將失敗。
+0

嗯。在答案之外的任何地方都沒有提及'fflush(stdin)'。 – 2013-03-18 19:30:11

+0

我編輯fflush(標準輸出),這只是我老師試圖解決這個問題。 – abaratham 2013-03-18 19:32:33

-1

當然這應該是

if (input != 5) 
     break; 

我覺得你的邏輯是錯誤的。

+1

現在有兩個人說過,我對運動不清楚嗎?我的邏輯很好,除非break在C++中比在java中有所不同,我對自己的邏輯充滿信心。問題在於程序甚至不會暫停輸入。 – abaratham 2013-03-18 19:17:34

+0

我認爲你的描述有點混亂。要求一些只輸入五個的概念有點奇怪。但我誤解了。如果你的程序甚至沒有暫停輸入,那麼你的問題就在你發佈的代碼之外。 – john 2013-03-18 21:58:50

2

你的代碼工作完美的我(在Visual Studio 2012)當我改變notFivemain。您的問題必須位於此代碼之外(可能因爲cin處於損壞狀態,正如其他人所建議的那樣)。

+0

對於Visual Studio 2010,我可以說同樣的事情 – nabroyan 2013-03-18 19:15:38

1

改變這一行:

cin >> input 

要這樣:

if (! (cin >> input)) { 
    cout << "std::cin is in a bad state! Aborting!" << endl; 
    return; 
} 

你的描述是,如果一件壞事發生cin此代碼運行之前會發生什麼行爲。

編輯:

添加此相同的代碼來的更早cin用途,找出它的進入不良狀態。

發生這種情況的一個例子是,如果代碼試圖讀取int,用戶鍵入的一個字母。

您也可以撥打cin.clear();挽回cin工作狀態。

+0

ok,顯然「std :: cin處於不良狀態!」有小費嗎? – abaratham 2013-03-18 19:28:17

+0

@abaratham看我的編輯。 – 2013-03-18 19:32:17

+0

這是我唯一一次在程序 – abaratham 2013-03-18 19:37:13