Hi, me again!
I wish to tidy up strings from user input. I have done a bit of research and have most of this working except the tricky bit - converting all/any whitespace between words to 1 ' ' char.
For instance, using hyphen to represent spaces..
---John-----MacDonald-
should end up as
John-MacDonald
Here is my code, it is malfunctioning and I've been debugging but can't see where the fault lies, except that the str.erase (i) bit doesn't seem to work as I expect. I expect it to remove one character at position i. but it doesn't, it chops off the rest of the string normally.
void trimString(string &str)
{
// trim Leading whitespace
// inline int ? TODO
// str = " 345 89"
int i = 0;
do
if (str[i] != ' ' && str[i] != '\t')
break;
while (++i <= str.size());
str.erase(0, i); // now str = "345 89"
// trim trailing whitespace
i = str.size();
while (i-- >= 0)
if (str[i] != ' ' && str[i] != '\t')
break;
str.resize(++i); // no whitespace at end so str = "345 89"
// trim each remaining whitespace to 1 character
i = 0;
while (++i < str.size()-1 /* No check of last char needed*/) {
// first i==1 as first char != ' '
if (str[i] == ' ' || str[i] == '\t') {
cout << i; // Sanity check, correct value
++i;
cout << i; // Sanity check, correct value
if (str[i] == ' ' || str[i] == '\t') {
str.erase(i-1); // now str = "345" ERROR!!!
//str.erase(--i);
cout << i;
continue;
}
}
} // end while
}