-2

To begin with, I'm using Windows 8.1, Visual Studio 2013 Express and c++. Don't know which C++ standard I'm using though.

I'm completely new to programming so I might have missed some fundamental part in this function. I am making a 10-question quiz and this one is about when MJ passed away. I'm trying to make sure that the program won't crash if the user inputs something other than an int by using getline().

I learned about stringstream and to convert. It is supposed to convert "playerAnswer" to an int. I am using#include <iostream> #include <string> #include <sstream> and 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: ";
        }
    }
}

If you could make it work as intended and in a better way/with shorter code I'd be very interested to learn it :) Any input from you guys is appriciated!

/NickL

NickL
  • 3
  • 3
  • _"but this doesn't seem to work"_ is to vague to ask. Please provide a [MCVE](http://stackoverflow.com/help/mcve). Also see [here](http://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it) and [here](http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi). – πάντα ῥεῖ May 06 '15 at 20:47

1 Answers1

1

You aren't initializing your stringstream to use the string that the user input:

stringstream convHolder;

should be

stringstream convHolder(playerAnswer);
dwcanillas
  • 3,562
  • 2
  • 24
  • 33
  • Thank you. Small mistake but just couldn't see it. Now how do I close this question and choose your answer as the solution to the problem? – NickL May 07 '15 at 16:15
  • @NickL you click the check mark near the arrows/score of my answer – dwcanillas May 07 '15 at 16:17