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?

14th Sep 2016, 5:52 PM
Facundo Jurisich
Facundo Jurisich - avatar
6 Respuestas
+ 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.
14th Sep 2016, 6:03 PM
Name Less
Name Less - avatar
+ 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.
14th Sep 2016, 6:09 PM
Zen
Zen - avatar
+ 2
@Giovanni: the question has the C++ tag, why are you talking about Python?
14th Sep 2016, 6:30 PM
Zen
Zen - avatar
+ 1
#include <string> if (a.compare("Code") == 0)
14th Sep 2016, 5:57 PM
Zen
Zen - avatar
0
Thanks.
14th Sep 2016, 6:00 PM
Facundo Jurisich
Facundo Jurisich - avatar
0
Also, you forgot: return 0;
15th Oct 2016, 1:22 PM
Gabriele Donati
Gabriele Donati - avatar