使用整个可打印的ASCII字符集C rot-13

ROT-13 using the entire printable ASCII Character Set C++

本文关键字:ASCII 字符集 rot-13 打印      更新时间:2023-10-16

我正在尝试创建一个将使用整个可打印ASCII字符集的代码。我的问题是,当涉及到比" r"(r')打印为"?'"的字符时,它的打印正确。为什么我的代码允许" r"卷回到可打印的字符,而不是任何字符?(stuvwxyz {|}〜)

"请输入您的密码。

abcdefghijklmnopqrstuvwxyz {|}〜

nopqrstuvwxyz {|}〜!???????????????"

#include <iostream>
#include <string>
using namespace std;
void encrypt(string password)
{
int count = 0;
char i;
    for (count = 0; count < password.length(); count++)
    {
        i = password.at(count) + 13;
            if (i >= 127)
                {
                    i = 32 + (i - 126);
                    cout << i;
                }
            else 
                cout << i;          
    }
    return;
}
int main()
{
    string password;
    cout << "Please enter your password." << endl;
    cin >> password;
    encrypt(password);
    cout << "n";
    return 0;
}

您的目标平台已签名char,因此char中的有效值范围为-128 .. +127

因此,您的if (i >= 127)仅覆盖'r'(值114),对于's'i等于-128,而不是 128。并且您的if将是false,您将输出-128 char值。

一个Quick-Fix是将i声明为unsigned char,以在+0 .. +255上进行操作。如果您要仅支持有效的ASCII 7B输入,那么这足以使所有 13算术正确。

我也不确定为什么要执行32 + (i - 126);,这是要求r转换为!(33),跳过空间(32),这是可打印的ASCII字符。

因此,在应用这些修复程序并将代码简化了一点(朝C 样式)简化后,我以:

结尾
void encrypt(const string & password)
{
    for (unsigned char charToRot13 : password) {
        charToRot13 += 13;
        if (127 <= charToRot13) charToRot13 -= (127 - ' ');
        cout << charToRot13;
    }
}

进行输入 输出('r'现在映射到' '):

Please enter your password.
abcopqrstuvw
nop|}~ !"#$%

但是。Rot13的主要功能是,您可以通过同一操作加密和解密文本。IE。" abc" ->" nop" ->" abc" ->" nop" -> ...

您转换为整个ASCII范围会破坏该功能。因此,您可能想要的是覆盖整个+32 .. +126 ASCII值范围,这是其中的95个。95/2 = 47.5,不好。让我们删除空间,因为您已经通过该-126做到了这一点,因此您可能不想要它。然后加密的值范围为+33 .. +126 = 94。94/2 = 47,好。要获取整个ASCII范围的ROT13状加密(空间除外),您可以使用Rot47。

void encrypt(const string & password)
{
    for (unsigned char charToRot47 : password) {
        if (charToRot47 < 33 || 126 < charToRot47) {
            cout << "nERROR: detected invalid character.n";
            break;
        }
        charToRot47 += 47;
        if (126 < charToRot47) charToRot47 -= 94;
        cout << charToRot47;
    }
}

这将输出:

Please enter your password.
xyz{|}~!"#$%000000IJKLMNOPQRST
IJKLMNOPQRST______xyz{|}~!"#$%

(请注意如何使用'y' -> 'J' -> 'y' -> 'J' -> ...