deleting spaces from a string

Hello! I've written this code to erase all the spaces in a string, but it doesn't work if i type "a d f s f aa f" in ex.in. Can anyone help me solve this problem?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
#include <cctype>
#include <cstring>
using namespace std;
char s[1001];
ifstream in("ex.in");
ofstream out("ex.out");
int main()
{   int i;
in.getline(s,1001);
 for(i=0;s[i]!=0;i++)
     if(s[i]==' ')
      strcpy(s+i,s+i+1);

    out<<s;
    return 0;
}
There's a much simpler way of doing it.

1
2
3
4
5
string str = "a s b c d";

str.erase(remove(str.begin(), str.end(), ' '), str.end());
    
cout << str << endl;
Thank you, it's always nice to learn something new, but I am not allowed to use this function since we haven't been taught at school about it yet.
oh yea Ive been there, kinda sucks. Unfortunately I have no idea how to do it manually or whatever its called, the way you're trying it. Ive seen some solutions on youtube/google, but they require two different character arrays, or character pointers. Are you allowed to do that?

Look if you can finds some answers here - https://www.google.se/#q=remove+spaces+from+string+C

atleast until someone who knows how to do this responds in this thread.

for(i=0;s[i]!=0;i++)
You want to be checking for '\0' and not 0. You may also want to make sure that i < 1001 in case for some reason the check didn't work.
Last edited on
Topic archived. No new replies allowed.