我正在尝试编写将 ASCII 转换为十进制、添加并转换回 ASCII 的软件

I'm trying to write software that converts ASCII to decimal, adds to it, and converts back to ASCII

本文关键字:转换 ASCII 添加 十进制 软件      更新时间:2023-10-16

我的代码有问题。这是我到目前为止所拥有的:

#include <iostream>
using namespace std;
int main()
{
char word[128];
int x = 0;
int v;
int shift;
int sv;
cin >> shift;
cin >> word;
while (word[x] != '')    // While the string isn't at the end... 
{
cout << int(word[x]) << " ";    // Transform the char to int
x++;
v = int(word[x]);
sv = v + shift;
cout << sv;
}
return 0;
}

这是凯撒密码,至少是其中的一部分。

当我输入时:

shift=1
word=f

我希望结果是:

102 103

相反,我最终得到这个:

102 1

我做错了什么?有更好的方法吗?

移动循环结束时递增x的行。在显示移位值之前,您正在递增x

while (word[x] != '')    // While the string isn't at the end... 
{
cout << int(word[x]) << " ";    // Transform the char to int
v = int(word[x]);
sv = v + shift;
cout << sv;
x++;
}

循环计数器通常在完成所有处理后在循环结束时递增。在您的情况下,x充当循环计数器,因为它正在确定while循环的条件。

因此,语句x++应该在所有处理之后出现,即在最后一次cout之后。

在 for 循环的情况下,

iteration_expression在循环的每次迭代之后和重新评估条件之前执行。通常,这是递增循环计数器的表达式

因此,您可以将上述while更改为for如下所示:

for(x = 0; word[x] != ''; x++)

然后,您不必在循环内递增x