编码凯撒加密代码要求输入两次密钥?
Coding caesar encryption code asks for key twice?
我实现了 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
%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");
}
}
我实现了 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
%d
忽略换行符 - stdin 中的换行符将保留,如果您的格式是 %d\n
,则需要输入两次。
和 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");
}
}