getline function and get rid of escape characters

Hello forum

I am reading line from a file using getline and I want to trim any escape characters from the string read by getline. Any hint on that ?

Thanks
I wonder what escape characters you mean
if the escape characters are allways the same you can set the 3rd parameter of getline to be the first of the escape characters and then ignore the next x characters (where x is the amount of escape characters - 1)
Last edited on
What if I want get rid of all the escape sequences as described in the following link:

http://en.cppreference.com/w/cpp/language/escape
getting rid of them is not the same as trimming...
to trim characters means to remove them from both ends of the string

To me that looks like a std::remove_if
you might want to have only numbers and letters in your string, you can use a lambda function in combination with std::erase and std::remove_if:
1
2
3
4
// remove if it is no space and no alphanumeric character
str.erase(std::remove_if(str.begin(), str.end(),
    [](char c) { return !(std::isspace(c) || std::isalnum(c)); } ),
    str.end());


if you know exactly what characters to ban you can make a string and bind that string to the lambda function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Example program
#include <iostream>
#include <string>
#include <functional> 
#include <algorithm> 

int main()
{
    std::string str = "Hello world, how are you?";
    
    str.erase(std::remove_if(str.begin(), str.end(), 
        std::bind([](char c, std::string chars) 
            { 
                return chars.find_first_of(c) != std::string::npos; 
            }, std::placeholders::_1, "aeiou")
        ),
        str.end()
    );
    
    std::cout << str << std::endl;
}

Last edited on
Topic archived. No new replies allowed.