hi heys, i am trying to remove beginning and the end whitespace in one file, and output the result to another file. But i am confused about how to remove whitespace. i need to make a function to do it. It should use string, anyone can help me ?
here is my code.
You are multiply confused. You appear to try to open two input files: one in main() and the other via a function. You do nothing with the latter. Similarly with output.
Please explain more clearly exactly what white space you are trying to remove.
Here is a simple trim routine. if you want to keep all the internals instead, you can replace that bit with a substring and it would be simpler and faster. I am sure it can be made better; as I said, it is a quick/simple one.
void trim(string &s, char c, bool keepinternal = true)
{ //keepinternal true means keep one copy of multiples inside
//while false means to remove all copies. ALL leading and trailing (even multiples)
//are removed regardless.
size_t dx; size_t i; size_t j;
if(keepinternal == false)
{ //completely eliminates the character c from the string.
s.erase(std::remove(s.begin(), s.end(), c), s.end());
return;
}
//trim leading and trailing and internal
dx = 0; i = s.length()-1;
while(s[dx] == c) {dx++;} //find the first letter that is not c
while(s[i] == c) {i--;} //find the last letter that is not c
string temp = s; s = ""; //copy s into temp and set s to empty string
for(j = dx; j<i+1; j++)
{ //for all the letters between the first not c up to the last not c, copy back into s
//unless there are 2+ in a row, then only get the first one.
if(temp[j]!=c || (temp[j]==c && temp[j+1]!=c))//keeps 1 copy per group of 1 or more cs internally
s += temp[j];
}
}