0

C++ How do I use if and else with strings?

Im kinda new at programming and I think I didnt saw it yet. Tried something like: ... cin >> name; if (name = kamil) { cout<<"hey"<<endl; } ...

15th Dec 2016, 9:25 PM
Krzysztof P.
4 Respuestas
+ 3
string name; cout << "Enter your name : "; cin >> name; if (name == "kamil" ) { cout << "Hello " << name << endl; } remember to put double quotes when using strings.. :)
15th Dec 2016, 9:46 PM
Fluffy Rabbit
Fluffy Rabbit - avatar
+ 1
1) when you compare something, use == or you will reassign a variable. = is assignment == is comparison 2) when you compare string vars with string literals, use double quotes on literals, otherwise compiler treats it as a variable name if (name == "kamil") { ... } 3) else statement is used with strings as with anything - statements inside it are executed in case when condition inside if statement evaluates to false. summary code: string name; cin >> name; if (name == "Jake") { cout << "wassup dude!" << endl; } else { cout << "who the hell are you?" << endl; }
15th Dec 2016, 9:52 PM
Demeth
Demeth - avatar
+ 1
Fluffy and Demeth's answers are correct, but only for std library string objects. The following for example will fail: char s[] = "Jack" ; if(s == "Jack") //You won't get here... else //You'll get here... The reason is that s is the pointer value (the name of an array resolves to the address of the array). Also, the reason it works for string objects is that string objects have overloaded the equality == operator in the string class. Char arrays are not classes so all the comparison do is compare the pointer values. To do a comparison on a char array you can use the strcmp function like this: if(strcmp(s, "Jack") == 0) //They are equal... else //They are not... You'll notice strcmp(..) returns 0 when the 2 strings are the same. You can also use memcmp(..), but then you have to specify the length as well.
16th Dec 2016, 12:34 AM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
Thanks everyone :)
16th Dec 2016, 10:45 AM
Krzysztof P.