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