Also. When you send in a string like that, it sends in a copy, so its already a different string. So do you have to create another one?
1 2 3 4 5
string filter (string s){
s.erase(remove(s.begin(), s.end(), ' '), s.end());
return s;
} /* if you have to create a new string. Just make the new string equal "s" and then do
switch out all the "s" for the new string.*/
string filter(string s){ // recieve a copy of string begin.
s.erase(remove(s.begin(), s.end(), ' '), s.end()); // remove all the spaces.
return s; // return the copy and place it in string begin
}
int main(){
string begin; // create string
cout << "Enter a string: "; // tell user to input string
getline(cin, begin); // input string
begin = filter(begin); // call the function and give it a copy of string begin. And whatever
// it returns, put it in put it in string begin.
cout << begin << endl; // output begin
system("pause");
}
I'm just trying to get the code you sent to compile. Line 2 of your code says there is an error:
error C2660: 'remove' : function does not take 3 arguments
After that I can figure out the rest.
#include <iostream>//for std::cout and std::cin
#include <string>//for std::string
#include <cctype>//for isalpha function
usingnamespace std;
string filter(string& s)
{
//it's essential to continue calculating the string size, given we'll likely be removing elements
for(int i = 0; i < s.size(); i++)
{
if(!isalpha(s[i])) s.erase(i, 1);//if element is not part of the alphabet, remove it
}
return s;
}
int main(void)
{
string line;
getline(cin, line);//read a whole line of input
string n = filter(line);
cout << endl << n;
return 0;
}
The getline() function reads a whole line of input, not just non-space characters as the >> operator would. This allows the line string to contain spaces as well. Since the filter function returns a string, we store the returned value in string n. We can then output n to the screen. The line string was passed by reference, so it was changed by the filter function. So line and n would contain the same information.