String Help in Parts

How do I output specific parts of a string that I don't specifically know what is assigned to it. Like the information assigned to the string is determined by the person running the program. Specifically here is the start of my program

string name;

cout >> "please enter your full name: " >> name >> endl;
getline (cin, name);


I want to take that full name and output only parts of it. Specifically the first, middle, and last names on separate lines.
1
2
3
cout << name[0] << endl;
cout << name[1] << endl;
cout << name[2] << endl;
that would only give me the first, second, and third letters.
...yeah, that only works after you've used a split function. A cheap, but functional implementation could look like this:
1
2
3
4
5
6
7
8
#include <vector>
#include <sstream>
#include <iterator>
vector<string> split(const string& str)
{
  stringstream ss(str);
  return vector<string>(istream_iterator<string>(ss),istream_iterator<string>());
}


and then:
1
2
3
4
vector<string> parts=split(name);
cout << parts[0] << endl;
cout << parts[1] << endl;
cout << parts[2] << endl;

The above still needs some checks, as I assume that not everyone has a middle name.
For this project I'm only allowed to use string functions and operators. We haven't talked about split fuctions yet.
And I doubt you ever will. A split function is just a function that splits a string into several parts using a delimiter (a space here (and other whitespace)). It has nothing to do with C++ itself. Instead of using istream iterators, you can just look for the spaces manually and use substr.

You can also do it using operator>>:

1
2
3
stringstream ss(str);
string first,middle,last;
ss >> first >> middle >> last;


...which also works directly with cin.
Last edited on
here is my current program and it's not running:

string name,firstName,middleName,lastName;



cout << "Please enter your full name: " << name;
getline (cin, name);
istringstream iss(name);
iss >> firstName;
iss >> middleName;
iss >> lastName;
cout << "\n";
cout << firstName << endl;



it says that istringstream and iss aren't allowed. nor are stringstream or ss.
so it allows me to use iostream but then says that name isn't defined when i have:

iostream iss(name);
Did you include <sstream>?
Topic archived. No new replies allowed.