title: Remove extra white spaces in C++
body: <p>I tried to write a script that removes extra white spaces but I didn't manage to finish it. </p>
  
  <p>Basically I want to transform <code>abc  sssd g g sdg    gg  gf</code> into <code>abc sssd g g sdg gg gf</code>.</p>
  
  <p>In languages like PHP or C#, it would be very easy, but not in C++, I see. This is my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;cstring&gt;
  #include &lt;unistd.h&gt;
  #include &lt;string.h&gt;
  
  char* trim3(char* s) {
      int l = strlen(s);
  
      while(isspace(s[l - 1])) --l;
      while(* s &amp;&amp; isspace(* s)) ++s, --l;
  
      return strndup(s, l);
  }
  
  char *str_replace(char * t1, char * t2, char * t6)
  {
      char*t4;
      char*t5=(char *)malloc(10);
      memset(t5, 0, 10);
      while(strstr(t6,t1))
      {
          t4=strstr(t6,t1);
          strncpy(t5+strlen(t5),t6,t4-t6);
          strcat(t5,t2);
          t4+=strlen(t1);
          t6=t4;
      }
  
      return strcat(t5,t4);
  }
  
  void remove_extra_whitespaces(char* input,char* output)
  {
      char* inputPtr = input; // init inputPtr always at the last moment.
      int spacecount = 0;
      while(*inputPtr != '\0')
      {
          char* substr;
          strncpy(substr, inputPtr+0, 1);
  
          if(substr == " ")
          {
              spacecount++;
          }
          else
          {
              spacecount = 0;
          }
  
          printf("[%p] -&gt; %d\n",*substr,spacecount);
  
          // Assume the string last with \0
          // some code
          inputPtr++; // After "some code" (instead of what you wrote).
      }   
  }
  
  int main(int argc, char **argv)
  {
      printf("testing 2 ..\n");
  
      char input[0x255] = "asfa sas    f f dgdgd  dg   ggg";
      char output[0x255] = "NO_OUTPUT_YET";
      remove_extra_whitespaces(input,output);
  
      return 1;
  }
  </code></pre>
  
  <p>It doesn't work. I tried several methods. What I am trying to do is to iterate the string letter by letter and dump it in another string as long as there is only one space in a row; if there are two spaces, don't write the second character to the new string.</p>
  
  <p>How can I solve this?</p>