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 . . .