String Help in Parts

Feb 1, 2012 at 10:07pm
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.
Feb 1, 2012 at 10:16pm
1
2
3
cout << name[0] << endl;
cout << name[1] << endl;
cout << name[2] << endl;
Feb 1, 2012 at 10:21pm
that would only give me the first, second, and third letters.
Feb 1, 2012 at 10:30pm
...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.
Feb 1, 2012 at 10:40pm
For this project I'm only allowed to use string functions and operators. We haven't talked about split fuctions yet.
Feb 1, 2012 at 10:44pm
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 Feb 1, 2012 at 10:49pm
Feb 1, 2012 at 11:03pm
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;



Feb 1, 2012 at 11:06pm
it says that istringstream and iss aren't allowed. nor are stringstream or ss.
Feb 1, 2012 at 11:09pm
so it allows me to use iostream but then says that name isn't defined when i have:

iostream iss(name);
Feb 1, 2012 at 11:22pm
Did you include <sstream>?
Topic archived. No new replies allowed.