我有关于 scanf
字符串的问题。我正在完成有关编码 Vigenere 密码的练习。
用其他语言很容易解决,但在 C 中我遇到了麻烦,我不知道为什么会这样。
这是我的代码。
#include<stdio.h>
#include<string.h>
main()
{
char mes[1000];
char key[100];
int n=strlen(mes);
int cipher[n],i,j=0;
printf("Enter message \n");
scanf("%s",mes);
printf("Enter keyword \n");
scanf("%s",key);
printf("len message= %d \n",strlen(mes));
for(i=0;i<strlen(mes);++i)
{
mes[i]=toupper(mes[i]);
key[j]=toupper(key[j]);
if(j==strlen(key))
j=0;
cipher[i]=((mes[i]-0x41)+(key[j]-0x41)) % 26;
printf("%c",cipher[i]+0x41);
++j;}
printf("\n");
}
如果 mes
数组输入小于 16 个字符,我的代码运行良好,但如果 mes
输入更大,程序将无限循环。我不知道为什么。
如果我将 cipher
数组的类型更改为 char 类型,它似乎工作得更好,但结果仍然有错误的输出,如下所示:
Enter message
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Enter keyword
eeeeeeeeeeeeeeeeeee
len of message= 45
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE�EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEAEEEEEEE
你能解释一下吗:
1) 如果 cipher
数组是 int
类型,为什么我的代码会出错?
2) 如果cipher
是char,输出更好,但为什么输出错误?
最佳答案
几个问题:
为
cipher
分配内存无法正常工作int n=strlen(mes); // mes has nothing now..so n=0! int cipher[n],i,j=0;
回滚
j
应该在增量之后完成。
在你读完两个输入后放置这个片段..它应该适用于任何长度<100
int cipher[strlen(mes)];
for(i=0;i<strlen(mes);++i)
{
mes[i]=toupper(mes[i]);
key[j]=toupper(key[j]);
cipher[i]=((mes[i]-'A')+(key[j]-'A')) % 26; //use 'A' for better readability
printf("%c",cipher[i]+'A');
++j;
if(j==strlen(key))
j=0;
}
关于C编程,由于scanf导致的错误循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23320842/