+ 2

How to evaluate or compare strings

Hello. I've just started learning C++ so I apologise in advance if my question is simple and/or dumb. I'd like to write a program that will execute a statement if a certain condition (determined by a character variable) is met. To make this easier to understand, I've added the code bellow: #include <iostream> #include <string> //I've tried with and without this chunk to no avail using namespace std; int main() { string trigger = "Pink flamingo"; string usrName; cout << "Greetings. Please input your name:" << endl; cin >> usrName; //user inputs their name //the idea is that this conditional is executed when usrName is the same as trigger if (usrName == trigger){ cout << "I'm sorry but I do believe that is a lie. \n" << endl; } cout << "Thanks " << usrName << "!" << endl; return 0; } One thing I've noticed is that if I change the program so that it behaves the same way but using Pink instead of Pink flamingo, it will work. Could someone please explain to me why this isn't working or what needs to be changed to make it work? Many thanks

12th Mar 2019, 3:59 AM
Tom
Tom - avatar
3 odpowiedzi
+ 2
I wasn’t sure, but was curious, so did a search and found this: https://www.programiz.com/cpp-programming/strings
12th Mar 2019, 4:33 AM
Mike
Mike - avatar
+ 2
You got it. The space was a terminating character. I was going to just post the revised line you would need but I found that page a good read and figured you’d probably want to read it too.
12th Mar 2019, 1:15 PM
Mike
Mike - avatar
+ 1
Thank you Mike! While I'm not entirely sure why using plain old cin >> usrName; didn't work, the link you sent provided me with a command that works (check example 3). The command for anyone who's interested is: getline(cin, usrName); //please note that usrName was a previously defined string variable I hope someone could confirm this, but if I understood correctly, according to the link the space in "Pink flamingo" ends up being considered as a terminating character (essentially something that says "stop here!") and only "Pink" was being assigned to the variable "usrName" which would then not be considered the same as the "trigger" variable and therefore wouldn't produce the desired output.
12th Mar 2019, 5:07 AM
Tom
Tom - avatar