New to c++ and it my poll maker isnt working

I am trying to make an extreemly basic poll maker and when i compile it, it works but if you imput more than one word for the string poll_question, the second, third, and fourth will flow into the strings answer1 answer2 and answer3 and if i put more than 5 words the code continualy repeats its self causing you to have to click to close, here is the code so far:


#include <iostream>
#include <string>

using namespace std;

int main()
{
string poll_question, answer1, answer2, answer3;
cout << "Welcome to the poll maker 9000!" << endl;
cout << "you can make a poll with 3 posible answers" << endl;
cout << "enter the question please" << endl;
cin >> poll_question;
cout << poll_question << endl;
cout << "enter the 1st answer" << endl;
cin >> answer1;
cout << answer1 << endl;
cout << "enter the 2nd" << endl;
cin >> answer2;
cout << answer2 << endl;
cout << "now the 3rd" << endl;
cin >> answer3;
cout << answer3 << endl;
cout << "the pole shall start now" << endl;
cout << poll_question << endl;
cout << "1. " << answer1 << endl;
cout << "2. " << answer2 << endl;
cout << "3. " << answer3 << endl;
cout << " " << endl;
int opinion;
int a1t, a2t, a3t;
a1t = 0;
a2t = 0;
a3t = 0;
while ( opinion != 0 )
{
cout << "Enter your answer or enter the number 0 to display the end result" << endl;
cin >> opinion;
if ( opinion == 1 )
{
a1t = a1t + 1;
cout << "answer 1 selected" << endl;
}
else if ( opinion == 2 )
{
a2t = a2t + 1;
cout << "answer 2 selected" << endl;
}
else if ( opinion == 3 )
{
a3t = a3t + 1;
cout << "answer 3 selected" << endl;
}
else
{
cout << "invalid input" << endl;
}
cout << "answer 1 selected " << a1t << " many times" << endl;
cout << "answer 2 selected " << a2t << " many times" << endl;
cout << "answer 3 selected " << a3t << " many times" << endl;
}
return 0;
}

any ideas thoughts or tips help,
thanks
allen
That is because you are using cin >> which only gets the input until a space is reached. In this case you will want to use getline to get the entire string.

getline(cin, poll_question);

Also while ( opinion != 0 ) may cause some problems as you have not declared opinion at that point, either change it to a do-while loop or give opinion some sort of starting value.
@Allen

Code tags would be good, use the <> button on the right under format.

Also consider using a switch instead of a load of else-if's.

Edit: As James was saying about declaring & initialising, I would add the following:

My mantra is "Declare, initialise & comment each variable on it's own line."

HTH
Last edited on
thanks a ton james and the ideas man
allen
Topic archived. No new replies allowed.