2017-04-26 84 views
-2

我寫了一個基本的程序,類似於ELIZA(在線治療師)簡單的問題和答案,但我堅持到底。後cin >>回答;我不能寫任何東西。如果有人能幫助它,將不勝感激!也與我一起,即時通訊編程新手。C++無法在cin後輸入>>回答;

int main() { 
    short number; 
    string color; 
    string sport; 
    int answer; 
    string travel; 


    // Greets user 
    cout << "Hello, I'm Samantha" << endl; 
    // Asks user for their favorite sport 
    cout << "What's your favorite sport?"; 
    cin >> sport; 
    cout << "I like " << sport << " too!" << endl; 
    cout << "How about your favorite color?"; 
    cin >> color; 
    cout << "Not my favorite color but it's nice!" << endl; 
    cout << "Tell me something you've never told anyone before"; 
    cin >> answer; 
    cout << "Don't worry, your secret is safe with me!" << endl; 
    cout << "Hows your life going?"; 
    cin >> answer; 

return 0; 
} 
+1

你的程序在'cin >>回答'後結束......你期待它做什麼? –

+0

你在調試程序時看到了什麼?如果您還沒有嘗試過,請這麼做 – Fureeish

+3

您的意思是_「以前從未告訴過任何人的事情」_是數字嗎? – Chad

回答

2

您的名爲「answer」的變量具有數據類型整數。當你第一次提示用戶從控制檯輸入東西(顯然是一個字符串)時,cin對象嘗試用一個字符串初始化「answer」(可能是因爲提示沒有要求輸入數字),這會殺死cin對象將不允許對象接受指令...因此,下次您要使用它時,不會有cin對象。

只需將「答案」的數據類型更改爲字符串即可。

Dr t

+0

另外,請注意,如果你需要在修改'std :: cin'之後修改它,你可以使用['std :: cin.clear()'](http://stackoverflow.com/a/10877539/5386374 )清除錯誤標誌,然後嘗試讀取不同類型的數據,或者用['std :: cin.ignore()']將其刪除(http://stackoverflow.com/questions/25475384/when-和爲什麼-DO-I-需要使用的-CIN-忽視 - 在-C)。 –

+0

啊啊,非常感謝你! –