0
How do I use if with string?
I wrote this code, but it doesn't work: #include <iostream> using namespace std; int main() { string a; cout << "Write a text" << endl; cin >> a; if (a == "Code") {cout << "Good text"; } else { cout << "Bad text"; } } Even if I write "Code", the output is "Bad text", and I don't know why. Could someone give me the answer?
6 Answers
+ 3
well actually what you have is just fine however even string is case sensitive so the string Code needs to be caps in the input. however you can use the or operator to write in the lower case as well in the if statement. also Zens way works but if you don't understand his a.compare method I suggest you learn it before just using it.
+ 2
Hum, Name Less is entirely right, there is no need for compare here. == doesn't work for strings in C, but it does in C++. I got confused for a sec.
+ 2
@Giovanni: the question has the C++ tag, why are you talking about Python?
+ 1
#include <string>
if (a.compare("Code") == 0)
0
Thanks.
0
Also, you forgot: return 0;