hello, Im just trying to do a simple switch of last name using a string function.
I can simply put the function in the main and it will come out good, but when I'm trying to make in a function on its own. The function can only return the first name. Any help? this is my code below
hi gunner, is there any way to keep the spaces of the new name to one single space if the user input a name with a lot of spaces between them since with your code if there are a lot of spaces between the original name then it will read for that many spaces.
#include <iostream>
#include <string>
usingnamespace std;
string newName(string o_n, string n_l_n){
// Set the substring until the white space as the first name
string new_name = o_n.substr(0, o_n.find(" "));
// Add the new last name
new_name += " " + n_l_n;
return new_name;
}
int main(){
string original_name, new_last_name;
cout << "Enter full name\n";
getline(cin, original_name);
cout << "Enter new last name\n";
getline(cin, new_last_name);
cout << newName(original_name, new_last_name) << '\n';
}
is there any way to keep the spaces of the new name to one single space
i think i see what you mean - you want to leave open the possibility that the new last name might be, for e.g. "parker bowles" etc but yet not let the user enter a whole paragraph! in that case frame the new_last_name entry around a do ... while loop: