【问题标题】:Coding caesar encryption code asks for key twice?编码凯撒加密代码两次要求密钥?
【发布时间】:2020-11-11 04:13:21
【问题描述】:

我实现了caesar-cipher算法,但我似乎没有掌握所有细节,因为当我运行程序时,它要求输入两次密钥!

#include <stdio.h>
#include <string.h>
#define SIZE 1024
char text[SIZE];
int text_2[SIZE];
int key;
int encoder(char text[SIZE]){
        printf("plaintext: \n");
        gets(text);
        for (int i = 0; i < strlen(text); ++i) {
            text_2[i] = (int) text[i];
            text_2[i] = text_2[i] + key;
            text[i] = (char) text_2[i];

        }
    return 0;
}

int main() {
    printf("enter the key: \n");
    scanf("%d\n",&key);
    if(key < 26 && key > 0){
        printf("nice!, now enter a word to encrypt it\n");
        gets(text); //this step is necessary to pass text onto encoder function.
        encoder(text);
        puts(text);
    } else{
       printf("Yeuch!!\n");
    }

}

输出的一个例子是:

enter the key: 
2 //I press 2 and nothing happens, then it asks for it again, hence why I have two 2's
2
nice!, now enter a word to encrypt it
plaintext: 
a
c

Process finished with exit code 0

【问题讨论】:

    标签: c algorithm cs50 caesar-cipher


    【解决方案1】:

    %d 忽略换行符 - stdin 中的换行符将保留,如果您的格式为%d\n,则需要两次回车。

    if 子句中的 gets(text) 删除换行符 - 您只需将格式更改为 %d

    解决方案:

    int main() {
        printf("enter the key: \n");
        scanf("%d", &key);
        if (key < 26 && key > 0) {
            printf("nice!, now enter a word to encrypt it\n");
            gets(text); // this step is necessary to pass text onto encoder
                        // function.
            encoder(text);
            puts(text);
        } else {
            printf("Yeuch!!\n");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-07
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 2016-08-30
      • 1970-01-01
      • 2020-05-31
      • 2014-02-06
      相关资源
      最近更新 更多