string input problems, using c++

I am having a problem with getting my input to take the first and last name it will only take my first name and output it so I type is John Smith and only John displays after words can you help me please.

here is my code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string username[2];

    cout << "Enter first and last name: ";
    cin >> username[2];
    cout << endl;
      
    cout << "Your name is " << username[2] << endl;

    return 0;
}
jschmuffAsked:
Who is Participating?
 
Infinity08Commented:
Use getline :

        http://www.cplusplus.com/reference/string/getline.html

cin breaks up its inpu based on whitespace. getline gets a whole line of input :

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string username[2];
    int counter = 0;

    cout << "Enter first and last name: ";
    getline(cin, username[counter]);
    cout << endl;
     
      cout << "Your name is " << username[counter] << endl;

      return 0;
}
0
 
josgoodCommented:
cin will stop extracting characters at the first delimiter.

try
    string firstName, lastName;
    cout << "Enter first and last name: ";
    cin >> firstName >> lastName;
    username[counter] = firstName + " " + lastName;

and you'll see what I mean.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.