Removing white space

Hey, i'm writing some code and i need the string entered to have all white space removed. I first tried this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    
    cout << "Please enter a string: ";
    getline(cin, str);
    
    for(int i=0; str[i]; i++)
     if(str[i] == ' ') str[i] = '\b';
     
    cout << str;
    
    cin.get();
    return 0;
}


but that was outputting the wrong code e.g. if i typed 'hello my name is' it outputs hellmnamis. I have a feeling it has something to do with the value of i and the position of the array shifting place because of it?

I then found this which i will probably use anyway:

1
2
3
4
5
6
7
8
9
// Here's the STL algorithm to remove spaces (or whatever char you specify)
  remove( s.begin(), s.end(), ' ' );

  cout << "I don't like spaces.\n"
       << s
       << endl;

  return EXIT_SUCCESS;
  }


Would still be nice to know why this doesn't work and if there is any way of making it work? Thanks.
if(str[i] == ' ') str[i] = '\b'; is replacing the spaces with a backspace which will remove from output the previous character

If you want to do this without STL algorithms you can try this:
1
2
for(int i=0; i<str.length(); i++)
     if(str[i] == ' ') str.erase(i,1);


Last edited on
With STL, remove() doesn't actually delete stuff -- so you must use erase() with it.
 
s.erase( remove( s.begin(), s.end(), ' ' ), s.end() );

Hope this helps.

[edit] fixed the code...
Last edited on
Bazzy: your code has a bug. Try using a string that has 2 consecutive embedded spaces.

('course Duoas' solution is 1 line of code :)
Thanks for both your inputs. Oh I see what you mean Bazzy, didn't realise that before. I'll bare that in mind Duoas!
need to specify the end pointer for erase to erase to the end.

s.erase(remove_if(s.begin(), s.end(), isspace), s.end());
for all white space
Yoinks! Nice catch Gumbercules

(Fixed above)
Topic archived. No new replies allowed.