Katie Stevers Katie Stevers - 1 month ago 19
C++ Question

String phrase ends at space?

I am wringing a simple code to learn more about string. When I ran my code it would not print my last name. Can someone explain why? I used string phrase to store it and it only appears to have stored my first name. Here is the code.

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting;
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
cin >> phrase;
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}

Answer

I used string phrase to store it and it only appears to have stored my first name.

That makes sense.

cin >> phrase;

will stop reading when it encounters a whitespace character in the input.

To read the full name you can use one of the following approaches.

  1. Use two calls to cin >>.

    std::string first_name;
    std::string last_name;
    cin >> first_name >> last_name;
    
  2. Use getline to read the entire line. getline will read everything in a a line, including whitespace characters.

    getline(cin, phrase);