我正在制作一个简单的代码来模拟Caesar的密码,而且我有一个奇怪的错误,尽管输出字符串fraseout[]
形成正确并且可以在最后一次打印它得到它的最后一个字符修剪。为什么会这样?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main (void)
{
printf("Insira a frase:\n");
char frase [256];
scanf("%s", frase);
int size = (int)strlen(frase);
printf("Insira o tamanho da divergência: \n");
int diff = 0;
scanf("%i", &diff);
char fraseout [size];
int i = 0;
for (i = 0; i<=size-1; i++)
{
int val = (int)frase[i];
if (val + diff > 126)
{
val = 31+diff-(126-val);
}
else if (val +diff < 32)
{
val = 127 + diff+(val-32);
}
else
{
val +=diff;
}
fraseout [i] = (char)val;
}
printf("\"%s\" -> \"%s\"\n", frase, fraseout);
return 0;
}
答案 0 :(得分:1)
有两个相关点,
strlen()
+ 1,因为strlen()
未考虑终止空。fraseout[i]
,最后一个元素设为0
或'\0'
,以使其可用作字符串。答案 1 :(得分:1)
fraseout
不足以保存NULL终止字节,所以你需要把它做得更大:
char fraseout [size+1];
此外,在构建fraseout
之后,您需要确保它已终止,否则您将打印垃圾:
fraseout[size] = '\0';