This is just for a school assignment. The instructions are that the user enters their first, middle, and last name. So there will be spaces in the appropriate places.
Could you elaborate a little more? I notice if I run the code breaking the string into two variables instead of 3, it works fine.
Yes, that would be convenient. My teacher wants the input to be one string variable that gets divided into 3 different string variables that are ouputed.
first is the location of the first space in the entire string
middle is the location of the second space in the ENTIRE string. You only search part of the string but it gives a location in reference to the entire string.
#include <cstdlib>
#include <iostream>
#include <string>
usingnamespace std;
int main(int argc, char *argv[])
{
string name, firstA, lastA, middleA, newName;
int first, last, middle;
cout << " Enter your full name: ";
getline(cin,name);
first = name.find(" ",0);
firstA = name.substr(0,first);
middle = name.find(" ",first+1);
middleA = name.substr(first+1,middle-1-first);
last = name.length();
lastA = name.substr(middle+1,last);
newName = lastA + ", " + firstA + " " + middleA;
cout << newName << " This string is " << newName.length()
<< " characters long "
<< endl << " The first name is " << first << " Characters long "
<< endl << " The last name is " << last-(middle+1)
<< " characters long " << endl << " The comma is located at position "
<< newName.find(",")+1 << endl;
cout << " To swap things around: ";
firstA.swap(lastA);
cout << lastA << " " << firstA << endl;
system("PAUSE");
return EXIT_SUCCESS;
}