I have pasted my cpp code below, my goal is removing the whitespace from my .txt file. Is someone able to provide suggestions and help me figure this out?

#include <iostream>
#include <sstream>
using namespace std;
string solve(string s) {
   string answer = "", temp;
   stringstream ss;
   ss << s;
    while(!ss.eof()) {
      ss >> temp;
      answer+=temp;
     }
   }
   return answer;
}
int main() {
   char buffer[100];
   FILE *fp = fopen("input.txt", "r");
   while (fgets(buffer, sizeof(buffer), fp))
   {
     cout << solve(fp);
   }
   fclose(fp);
   return (0);
}

Sorry, I don't know C++, but can you explain what isn't working with the code you have. Is the solve() function supposed to be removing the whitespace?

According to this StackOverflow question the solution is str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

You could also try using regex as so: str = regex_replace(str,regex("\\s"),""); which is the equivalent of how I would do it in PHP (my language of choice).

You can use something like this:

while ((c = getc(fp)) != EOF)
        if(c == 32) ....
commented: I've seen such before but most of the time I want a single space to remain. +16

If what you want to actually do is, as you mentioned in one of the comments, remove consecutive whitespaces, all you need to do is keep track if the last character you copied to the output was a whitespace and check if the current character is also a whitespace, then only copy it if it was not.

I use vim on files and often need to replace multiple spaces with a single space and use
%s/ / /g
Note: there are two blanks between the first two "/" characters - apparently the daniweb software condenses them to one blank! Then there is one blank between the last two "/" characters.

For the more general whitespace case, I'd have to be concerned about which of the different whitespace characters I'd want to leave there - and I'd probably have to do a lot more deciding - but to remove a string of whitespace characters and leave a single blank
%s/\s\s/ /g
would do it.

But to simply remove all whitespaces
%s/\s//g
would remove them all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.