-2

首先,我使用Windows 8.1,Visual Studio 2013 Express和C++。不知道我在用哪個C++標準。Stringstream將無法正確轉換

我完全不熟悉編程,所以我可能錯過了這個函數的一些基本部分。我正在做一個10個問題的測驗,這是關於MJ何時去世的。我試圖確保如果用戶使用getline()來輸入int以外的內容,程序不會崩潰。

我瞭解了stringstream並轉換。它應該將「playerAnswer」轉換爲int。 我使用#include <iostream>#include <string>#include <sstream>using namespace std;

int question_3() 
{ 

    cout << "Question 3:\n"; 

    string playerAnswer = ""; 
    int convertedAnswer = 0;  

    cout << "Which year did Michael Jackson die? 2008, 2009 or 2010?\n" \ 
      "Your answer: "; 

    while (true) 
    { 
     getline(cin, playerAnswer); 
     stringstream convHolder; // EDIT: Got an answer and it now works. 
            // Forgot (playerAnswer) in convHolder 
     if (convHolder >> convertedAnswer) 
     { 
      if (convertedAnswer == 2009) 
      { 
       cout << endl << "Correct! \nOn August 29 1958 the legend was born. \n" \ 
           "On June 25 2009 he passed away in his rented mansion in Holmby Hills.\n"; 
       cout << endl; 
       return 1; 
      } 
      else 
      { 
       cout << endl << "Wrong. \nOn August 29 1958 the legend was born. \n" \ 
           "On June 25 2009 he passed away in his rented mansion in Holmby Hills.\n"; 
       cout << endl; 
       return 0; 
      } 
     } 
     else 
     { 
      cout << "Invalid number, please try again: "; 
     } 
    } 
} 

如果你能按預期工作,以更好的方式/用較短的代碼,我會非常有興趣去學習吧:)從你們的任何輸入appriciated!

/NICKL

+0

_「,但這似乎並沒有不工作「_是模糊地問。請提供[MCVE](http://stackoverflow.com/help/mcve)。另見[這裏](http://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it)和[這裏] (http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi)。 –

回答

1

您還沒有初始化你的stringstream使用的字符串,用戶輸入:

stringstream convHolder; 

應該

stringstream convHolder(playerAnswer); 
+0

謝謝。小錯誤,但看不到它。現在我該如何解決這個問題並選擇你的答案作爲解決問題的辦法? – NickL

+0

@NickL你點擊箭頭旁邊的複選標記/我的答案分數 – dwcanillas

相關問題