Hi I am new to C++ and I'm trying to create a console program that quizzes you using some of my old quizzes. My only problem is when I get to questions where there are spaces between the word it messes up. Here's an example:

string answer1 = "anything\0that\0has\0mass\0and\0occupies\0space";
string userresponse1;
cout <<  "1.  Define matter.\n";
cin  >> userresponse1;
if (userresponse1 == answer1)
{
                  cout << "Correct" << endl;
                  score += 1;
}
else
{
    cout << "Incorrect" << endl;
}

I enter the answer, but it goes ahead and and answers the next question and the one following that. My question is can you compare strings with spaces in it?

Re: Help with strings 80 80

When you ask the user for data using cin >> , only the part up to the first white space (in this case the first word the user enters) will be stored in the variable. Use getline instead of >> in order to get a full line from the user.

Also, use spaces, not '\0', in answer1.

Re: Help with strings 80 80

Yes you can. More simply than you can imagine.
The only problem is that you shouldn't be playing with the null character '\0'.

string answer1 = "anything that has mass and occupies space";
string userresponse1;
cout << "1. Define matter.\n";
getline(cin,userresponse1);//<<<<<See the difference
if (userresponse1 == answer1)
{
cout << "Correct" << endl;
score += 1;
}
else
{
cout << "Incorrect" << endl;
}

The moral is, use getline when you know that the user response will include spaces.

Always post your code in the code tags:

[code=cplusplus] //your code goes here

[/code]

Re: Help with strings 80 80

Thank you so much. I'm sorry next time I'll remember to put code tags. This was my first post. Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.