0

I'm working on a project of splicing an inputted string of a name, and for some reason it's not working. Part of it is code copied from my book that supposedly works, so I'm stuck. Am I doing something wrong?

#include <iostream>
#include <string>

using namespace std;

void main()
{
    string name;
    int index;
    cout<<"Please enter your full name. ";
    cin>>name;

    cout<<"\n"<<endl;

    index = name.find(' ');
    cout<<"First Name: "<<name.substr(0, index)<<"          "<<name.substr(0, index).length()<<endl;
    name = name.substr(index+1, name.length()-1);

    index = name.find(' ');
    cout<<"Middle Name: "<<name.substr(0, index)<<"         "<<name.substr(0, index).length()<<endl;
    name = name.substr(index+1, name.length()-1);

    cout<<"Last Name: "<<name<<"                "<<name.length()<<endl;
}
  • 2
    Side note: Did you know that to print tab, you should write `\t` and not an actual tab in your string? – Shahbaz Dec 12 '11 at 19:25
  • 2
    How is it "not working", what input are you giving? What is the output? What is the expected output? – Chad Dec 12 '11 at 19:26
  • 3
    [The return type of `main()` is `int`, not `void`.](http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main) – James McNellis Dec 12 '11 at 19:28
  • 1
    The only thing I can see at first glance that you're doing wrong is that you failed to say what happens. "It's not working" is rather vague, couldn't you just paste some actual output from your program and say what you expected instead? – wolfgang Dec 12 '11 at 19:29
  • I'm assuming the expected output is everything after the first name. middle-last-whatever. –  Dec 12 '11 at 19:31

1 Answers1

7

Most peoples' names consist of at least two words. This will only get one of them:

cout<<"Please enter your full name. ";
cin>>name;

istream operator>> is whitespace delimited. Use getline instead:

std::getline(std::cin, name);

For your purposes, you could probably do this, which is simpler:

std::string first, middle, last;
std::cin >> first >> middle >> last;
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274