Search code examples
c++linuxunix

Removing whitespace from a string variable


So I've looked up various functions and ways to remove whitespaces from strings, but none of them seem to be working for me. Here's what I have right now:

string filename = filenamet;
//remove all whitespace
//filename.erase(remove(filename.begin(), filename.end(), isspace), filename.end());

where filenamet is a string variable, and as is filename. I've double checked all my includes, so they don't seem to be the problem either. Here's the compiler error I'm getting:

test.cpp: In function ‘void input(char*, char**)’:
test.cpp:256:68: error: cannot convert ‘std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ to ‘const char*’ for argument ‘1’ to ‘int remove(const char*)’ filename.erase(remove(filename.begin(), filename.end(), isspace), filename.end());

I've also tried it with remove_if without remove, but then I get this compiler error:

test.cpp: In function ‘void input(char*, char**)’:
test.cpp:256:71: error: ‘remove_if’ was not declared in this scope
     filename.erase(remove_if(filename.begin(), filename.end(), isspace), filename.end());

Any help is greatly appreciated!


Solution

  • std::string remove_char(const std::string &input, char to_remove){
        std::string output;
        for(unsigned i=0; i<input.size(); ++i)
            if(input[i]!=to_remove)
                output+=input[i];
        return output;
    }