I'm just learning all the string commands and I am super confused on how to use .find. The goal of this program is to take a user input of there name first mid last (uu-cap) and convert to Last, First Mi (with cap first letter).
I just need some guidance on the use of this member function. Thank you.
#include <iostream>
#include <string>
usingnamespace std;
string change(string);
int main()
{
string Name;
char choice;
//loop to get multiple names if user selects y/Y
do {
cout << "Enter a name first mi last \n";
getline(cin, Name);
change(Name);
cout << "You entered: " << Name;
cout << " It was converted to: " << change(Name) << endl;
cout << "Do you wish to enter another name? <Y/N> \n";
cin >> choice;
cin.ignore();
} while (toupper(choice) == 'Y');
return 0;
}
// string function to recieve string and convert to Last, First Mi
string change(string name)
{
string first, mid, last;
first = name.find(" "); // find first 0 - first "space"
mid = name.find(" ", '.'); // find mid from "space" to "."
last = name.find(" ", '0'); // find last from "space" to return/null
//makes the first position in first/mid/last capital
first[0] = toupper(first[0]);
mid[0] = toupper(mid[0]);
last[0] = toupper(last[0]);
string newName = last + ", " + first + " " + mid;
return newName;
}
so how would I use find to pull each string out of a random sentence from the user? I see how to find when I'm selecting something (like "W") but if the user can put what ever in, I'm not seeing how to get one word alone and move on to the next.
ignoring edge cases, find space, substr(0, result). find space from there, substr(previous end, result). etc. you may need to handle leading spaces, multiple spaces, etc.
you can also just let the machine do it for you.
cin >> first >> middle >> last;
will store the names in 3 strings and strips off any white space.
getline gets the whitespace, which you didn't really seem to want.
Yeah, so my original project used cin and assigned each input. It took me 2 mins and worked perfect. The problem was, I caught the fact we need to use .find to get each line from a full string.
So, I thought I was ignoring the edge casing with the original way.
1 2 3 4 5
string change(string name)
{
string first, mid, last;
first = name.find(" "); // find first 0 - first "space"
now I run substr(0, first) but that leads to nothing. are you essentially using the .find function to get the first string and then substr() for everything thing else.. or is it more like find, substr, find, substr, find substr?
thanks for all of your help. these strings are really getting confusing. I have been pretty solid on everything else.
Thank you for the response. I think I see what needs done now. I believe one of the big problems was, I wasn't making start and end variables from the beginning. thanks again