使用整个可打印的ASCII字符集C rot-13
ROT-13 using the entire printable ASCII Character Set C++
我正在尝试创建一个将使用整个可打印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' -> ...
)
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- ascii 和 unicode 在处理级别有什么区别吗?
- 在C++中使用 ASCII 代码将输入从小写转换为大写
- 弄清楚如何在C++中将整数读入 ASCII
- 如何修复艺术ASCII,我点击一个字母就可以了,但输入一个阶段艺术出来了
- 使用指针将 ASCII 值添加到整数
- 用于 ASCII 的环绕式 C++
- RE2 不匹配非 ASCII 字符
- 打印从 0 到 255 的所有 ASCII 字符
- C++ 电话号码字母拨号程序 - 语法错别字?还是非 ASCII 字符?
- 无符号字符打印其 ASCII 值
- Windows 非 ASCII 文件路径
- 非 ASCII 文件路径窗口
- C++ CUDA:如何将字节表示为字符或字符集?
- 我的程序将 26 个字母转换为 ascII 没有显示正确答案
- 我写的 ASCII 到二进制转换器C++向后显示二进制,如何使其正确显示?
- 使用整个可打印的ASCII字符集C rot-13