C编程,由于scanf导致的错误循环?

标签 c

我有关于 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,输出更好,但为什么输出错误?

最佳答案

几个问题:

  1. cipher 分配内存无法正常工作

    int n=strlen(mes); // mes has nothing now..so n=0! 
    int cipher[n],i,j=0;
    
  2. 回滚 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/

相关文章:

c - C中矩阵和 vector 乘法的优化

c - 有没有办法在 GCC 或 cl.exe 的预处理和编译之间插入一个步骤?

c - 生成带间隙的随机数

c - C 中的多线程使用线程安全随机数

c - Vim - YouCompleteMe RestartServer 不断关闭

php - 可以用 C 或 C++ 编写 HTML 表单

在 windows 和 linux 上编译

使用父宏的右括号的 C 预处理器

c - 为什么我对 connect() 的调用失败了?

c - 进程如何就 IPC 参数进行通信?