Inside the second while loop, use isspace (accounts for all kinds of whitespaces)
-> After you've found position of white space inside the while loop, write
1 2
|
if(!(isspace(s[pos-1])))
s.insert(' ');
|
s[pos-1]
is the index previous to the found index (index of the whitespace that was found).
isspace(s[pos-1])
checks whether the position is a whitespace character.
and lastly we enclose the entire expression with parenthesis and negate it with
!
.
So the if statement becomes: If the previous index is
not whitespace, execute block (which is
s.insert
in this case)
This is a good approach for the most part but is slower than iterating over every character manually, which you don't have to worry about but I'm just mentioning it so you know when find_first_of is not ideal.
Oh and one more thing. You haven't even mentioned a position for the insert! ;P
Have you tried compiling it?
Oh and another thing, you want to add an if condition inside the while loop itself to make sure that pos has a value. (pos gets -1 when no matches are found)