Search code examples
c++stringcin

Issue when std::cin to std::string with spaces


Just started learning C++ and encountered an issue with strings while doing an exercise.

So I initialized std::string phrase; while allowing the user to input and save the phrase to the string with std::cin >> phrase;. Now my issue comes when the inputted phrase has spaces, I noticed that the computer will only save the characters up till the first word only.

With the phrase "sunsets are great", the phrase.size() only came out to 7, so the following words after the first space were not saved.

The entire exercise is supposed to compare all of the letters in the whole inputted string with another set of values. Should I be using a different function for this?


Solution

  • I have also had this problem when i was first starting out. whenever you want to read a string i would use the getline.

    ie

    string phase
    cout << "enter phase" <<endl;
    getline(cin,phase);