-1

Well, I want to make a function which have encoding and decoding function. So, I studied about "rot-13 encoding" and solved it like this:

char* szTemp = "Hello World";
for (int i = 0; i < strlen(szTemp); i++)
{
    if       (szTemp[i] >= 'a' && szTemp[i] <= 'm') szTemp[i] += 13;
    else if  (szTemp[i] >= 'A' && szTemp[i] <= 'M') szTemp[i] += 13;
    else if  (szTemp[i] >= 'n' && szTemp[i] <= 'z') szTemp[i] -= 13;
    else if  (szTemp[i] >= 'N' && szTemp[i] <= 'Z') szTemp[i] -= 13;
}
MessageBox(szTemp);

But it have some error. What is it? Anyone help me!

3
  • 5
    You're trying to modify a read-only literal string. I'd start by fixing that. char szTemp[] = "Hello, World!";
    – WhozCraig
    Jul 23, 2016 at 5:43
  • char* szTemp is not read only. You just have to make sure you don't write past the size of the buffer. Jul 23, 2016 at 5:55
  • 1
    @DexStar memory it points to is read only. First line should not even compile on modern standards, but even in dark ages, attempt to modify string literal is UB. Jul 23, 2016 at 6:36

1 Answer 1

1

In MFC, it's all about the CString...

    CString sTemp = "Hello World";
    CString sResult = "";
    int nLength = sTemp.GetLength();
    char c;

    for ( int i = 0 ; i < nLength ; ++i )
    {
        c = sTemp[i];
        if       (c>= 'a' && c<= 'm') c+= 13;
        else if  (c>= 'A' && c<= 'M') c+= 13;
        else if  (c>= 'n' && c<= 'z') c-= 13;
        else if  (c>= 'N' && c<= 'Z') c-= 13;
        sResult += c;
    }

    AfxMessageBox( sResult );

It can also be done by accessing the buffer directly, in which case, you can use almost all of your original code. It looks something like this:

    CString sTemp = "Hello World";
    int nLength = sTemp.GetLength();

    // Limit scope of szTemp since it is not usable after 
    // the call to ReleaseBuffer
    {
        char* szTemp = sTemp.GetBuffer();

        for (int i = 0; i < nLength; i++)
        {
            if       (szTemp[i] >= 'a' && szTemp[i] <= 'm') szTemp[i] += 13;
            else if  (szTemp[i] >= 'A' && szTemp[i] <= 'M') szTemp[i] += 13;
            else if  (szTemp[i] >= 'n' && szTemp[i] <= 'z') szTemp[i] -= 13;
            else if  (szTemp[i] >= 'N' && szTemp[i] <= 'Z') szTemp[i] -= 13;
        }
        sTemp.ReleaseBuffer();
    }

    AfxMessageBox( sTemp );

Hope that helps, D*

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.