If/else run-time error

Hello,
I'm having trouble with my code. It compiles fine, but one of my if conditions isn't being recognized at run time. The issue is that if I type "computer science" in the terminal, it doesn't recognize it and outputs "That's cool! Mine is computer science." instead of the "mine too..." string.

Feel free to comment on any other issues (bad practice etc) if you see them. I'm pretty new to C++ and open to criticism. Roast me.

1
2
3
4
5
6
7
8
9
10
11
  cout << "What is your favorite subject? ";
  string fav_subject;
  cin >> fav_subject;
  if(fav_subject == "computer science")
  {
    cout << "Mine too! I am, after all, a computer!\nGoodbye\n";
  }
  else
  {
     cout << "That's cool! Mine is computer science.\nGoodbye!\n";
  }
Last edited on
Do you realize that the extraction operator>> by default stops processing when it encounters a whitespace character?
It’s because it only receives the computer instead of the computer science perche the space is where the input ends, try getline();
It works now! Thanks for the help. Also had to add cin.ignore() since this is a snippet from a larger bit of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cout << "What is your favorite subject?\n";
string fav_subject;
cin.ignore();
getline(cin,fav_subject);

if(fav_subject == "computer science")
{
    cout << "Mine too! I am, after all, a computer!\nGoodbye\n";
}

else
{
    cout << fav_subject << " is cool! Mine is computer science.\nGoodbye!\n";
}
Last edited on
Registered users can post here. Sign in or register to post.