Search code examples
c++compiler-errorswarningscompiler-warnings

error C2137 : Empty character constant in c++


Here is the code :

void SomeClass::SomeFunctionToCorrectName(CString &strName)
{
        
    //  Only alphabets (Aa-Zz), numbers(0-9), "_" (underscore) and "-" (hyphen) are allowed. 
                
        for(int nIndex = 0; nIndex < strName.GetLength(); nIndex++)
        {
            TCHAR currentChar = strName.GetAt(nIndex);
            
            if((currentChar >= _T('a') && currentChar <= _T('z')) ||
                (currentChar >= _T('A') && currentChar <= _T('Z')) ||
                (currentChar >= _T('0') && currentChar <= _T('9')) ||
                currentChar == _T('-') || currentChar == _T('_'))
            {
                continue;
            }
            strName.Replace(currentChar,_T(''));    
        }
}

This method removes anything extra in strName and only alphabets (Aa-Zz), numbers(0-9), "_" (underscore) and "-" (hyphen) are allowed. The if cases are to check those allowed conditions. If its not under the allowed conditions it will remove that.

For Eg desired i/p :"Hel*lo*World" and desired o/p : "HelloWorld"

But the following gives me error as follows :

error C2137: empty character constant

I can fix this error by using any of the three methods:
1. using '\0'
2. using ' ' (space in between ' ')
3. using ""[0]

but this introduces space while replacing.

Input :Hel*lo*World
Output :Hel lo World
Desired Output :HelloWorld

Can anyone suggest how can I get the desired result?


Solution

  • If you want to remove a specific character, then Replace is not the right method to use. As you've noticed, there is nothing reasonable to replace the character with.

    Instead you can use Remove like this:

    strName.Remove(currentChar);