Empty Character Constant

2019-09-05 01:48发布

问题:

Is there a way to bypass error C2137 on Visual Studio Community 2015? I am removing characters with stringstream but I do not want to replace them (even with a blank space), I want to erase them so, if I want to remove all 'o' in 'cool' it becomes 'cl' and not 'c l'. I saw in Stroustrup's book he wrote a if (...) ch = ''; but my compiler returns me an error and my best proxy is white space that's still unacceptable.

Here's my function with C2137:

string rem_vow(string& s)
{
    for (char& c : s)
    {
        switch (c)
        {
        case 'A': case 'a': case 'E': case 'e': case 'I': 
        case 'i': case 'O': case 'o': case 'U': case 'u':
            c = '';
            break;
        default:
            break;
        }
    }

    return s;
}

EDIT:

That's the code I saw in the book:

Thank you in advance

回答1:

No, in order to remove a character in a string you will have to move the rest of the string one step, you cannot simple replace it with "empty" character. You could use the erase method though, but then you should probably not do that while iterating the string.

What you probably should do is to build a new string as you traverse the original string, something like:

string rem_vow(string const& s)
{
    string res;

    for (char c : s)
    {
        switch (c)
        {
        case 'A': case 'a': case 'E': case 'e': case 'I':
        case 'i': case 'O': case 'o': case 'U': case 'u':
            //c = ' ';
            break;
        default:
            res.push_back(c);
            break;
        }
    }

    return res;
}