Another problem with if and string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Another problem with if and string

I have this code: #include <iostream> #include <string> using namespace std; int main () { string a = "Learn code"; cin >> a; if (a == "Learn code" || a == "learn code") { cout << "Good"; } else { cout << "Bad" } } Why if I write Learn code the output is bad? It's strange because if I delete the cin, it says good, but when I write exactly the same with cin it says bad. I tried cin with only one word and it works perfectly, but when there are more than one word, the output is always Bad.

14th Sep 2016, 9:28 PM
Facundo Jurisich
Facundo Jurisich - avatar
5 Answers
+ 1
char a[100]; cin.getline(a, sizeof(a)); Use that instead of cin >> a.
14th Sep 2016, 9:59 PM
Zen
Zen - avatar
0
Sorry, I don't understand, I'm learning the functions now, so I guess I still have to learn.
14th Sep 2016, 9:44 PM
Facundo Jurisich
Facundo Jurisich - avatar
0
If you want to use the getline command, it (very layman terms) follows the syntax getline(input, output). See if that helps. The reason yours isn't working right now is because >> does not simply assign input to 'a'. It is a right-shift bitwise operator. Print the 'a' variable after the line cin >> a; and you will see what I mean.
14th Sep 2016, 10:24 PM
Ryne
Ryne - avatar
0
I printed a after cin, and the output was only the first word. I think I understand now, thanks!
14th Sep 2016, 11:22 PM
Facundo Jurisich
Facundo Jurisich - avatar
0
because cin function only work till space after space it doesn't take any character
31st Oct 2016, 4:17 PM
Gaurav Arora
Gaurav Arora - avatar