Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 433
  • Last Modified:

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;
}
0
jschmuff
Asked:
jschmuff
1 Solution
 
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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now