I'm fairly new to the C++ language, and I've been having difficulty with user-input in relation to if statements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
int main ()
{ cout << "What is your favourite colour? ";
string colour;
cin >> colour;
cout << "That's fantastic! "; cout << colour; cout << " is my favourite colour, as well!";
cout << "Are you an "; int adventurer; cout << "adventurer, "; int politician; cout << "policitian, or "; int dreamer; cout << "dreamer?";
string mystring;
cin >> mystring;
if (mystring == adventurer)
cout << "That's great!";
return 0;
}
I can't seem to get the if statement to function properly. I get the error message
-- C:\aCodeBlocks\Untitled4.cpp|14|error: could not convert 'mystring' from 'std::string {aka std::basic_string<char>}' to 'bool'| --
and I'm hopelessly stuck. Any help would be appreciated. Thank you!
Also line 8 and 12 cin >> colour; and cin >> mystring; attempts to read a string with cin. This is ok, until the user enters something like "light blue" - in which case cin will stop reading at the first whitespace between light and blue, only reading light in the variable colour. To avoid this from happening, while accepting input from user that could possibly have a space, use:
getline(cin, colour);
to read the enter string before the carriage or return (enter) symbol is found.
Thank you! That worked just fine, however...
...whenever I type in "adventurer" for the input prompt on the second question, I don't get anything.
When I type in anything other than adventurer, I get the intended response of "That's great!".
I appreciate the advice greatly, but do you know how to solve this problem? I would like for the user, when they input either "adventurer", "dreamer", or "politician" to get a response corresponding to their respective input. When I tell the user to use numbers (i.e. "1 for adventurer, 2 for politician, etc.) it works, but I'd prefer the use of non-numerical characters to the numbers. Is there any way around this, or perhaps I'm once again missing something?