【问题标题】:How can I do "rot-13 decode" in MFC?如何在 MFC 中进行“rot-13 解码”?
【发布时间】:2016-07-23 05:36:44
【问题描述】:

好吧,我想做一个具有编码和解码功能的函数。 所以,我研究了“rot-13 encoding”并解决了这个问题:

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);

但它有一些错误。它是什么?谁来帮帮我!

【问题讨论】:

  • 您正在尝试modify a read-only literal string。我会先解决这个问题。 char szTemp[] = "Hello, World!";
  • char* szTemp只读的。你只需要确保你写的内容不会超过缓冲区的大小。
  • @DexStar 指向的内存是只读的。第一行甚至不应该按照现代标准编译,但即使在黑暗时代,尝试修改字符串文字也是 UB。

标签: c++ mfc


【解决方案1】:

在 MFC 中,一切都是关于 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 );

也可以通过直接访问缓冲区来完成,在这种情况下,您几乎可以使用所有原始代码。它看起来像这样:

    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 );

希望对您有所帮助, D*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多