I'm trying to isolate a first name, space, middle initial, space, and last name. The full name is given by the user. The only problem I'm having is isolating the middle initial. Current code:

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string forwardname,first,mi,last;
int space1pos,space2pos;
cout<<"Enter your first name, middle initial, and last name, separated by";
cout<<" a space: "<<endl;
getline(cin,forwardname);
space1pos=forwardname.find(' ');
space2pos=forwardname.find(' ',space1pos+1);
first=forwardname.substr(0,space1pos);
mi=forwardname.substr(space1pos+1,space2pos);
last=forwardname.substr(space2pos+1);
system("PAUSE");
return EXIT_SUCCESS;}

If I were to do...

cout<<first<<endl;

I would get the first name.
If I were to do...

cout<<last<<endl;

I would get the last name.

However, when I try to cout the middle initial

cout<<mi<<endl;

the machine would output the middle initial, the second space, AND some of the last name.
Let me edit the code, to make this clearer:

.....
cout<<first<<endl;
cout<<mi<<endl;
cout<<last<<endl;
system("PAUSE");
return EXIT_SUCCESS;}

Here is the console output:

Enter your first name, middle initial, and last name, separated by a space:
Thomas G Hooper
Thomas
G Hooper
Hooper
Press any key to continue . . .

Recommended Answers

All 4 Replies

mi=forwardname.substr(space1pos+1,space2pos); is your culprit. Is the 2nd parameter the ending location or is it number of characters?

I actually figured out what the problem with my code was.

mi=forwardname.substr(space1pos+1,space2pos);

Both need to be integers. Space1pos+1 will first store the middle initial, but instead of writing space2pos (which is a number a bit greater than 1 {completely forgot about this, b/c i'm an idiot}), I should have written out the number 1 (which I did a little bit after looking through my C++ manual and fiddling with the code). My program is finished now. You hit the nail on the head with your post, though.

To directly answer your question, though: I wanted my second parameter to cut off the stream of data, right after the middle initial; so, I just needed to replace it with a 1, instead.

Yep... :icon_mrgreen:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.