gpt4 book ai didi

C 语言的凯撒密码

转载 作者:行者123 更新时间:2023-11-30 17:34:49 25 4
gpt4 key购买 nike

在这个凯撒密码中,我该如何制作它,以便它读取空格、特殊字符(!@#$* ...)和数字并保持它们原样并打印它们?另外,我在 fgets while 循环的末尾放置了一个 fprintf(file2,"\n") ,它确实开始了一个新行,但它总是在上一行的末尾打印一个奇怪的字符。

#include <stdio.h>

int main (int argc, char *argv[]) {

char caesar[256];
int shift;
FILE *file1=fopen(argv[1],"r");
FILE *file2=fopen(argv[2],"w");

sscanf(argv[3], "%d", &shift);


while(fgets(caesar,sizeof(caesar),file1)!=NULL){
int i = 0;
while (caesar[i] != '\0') {
if (((caesar[i] + shift) >= 65 && (caesar[i] + shift) <= 90)||((caesar[i] + shift) >= 97 && (caesar[i] + shift) <= 122)) {
caesar[i] += (shift);
}
else {
caesar[i] += (shift - 26);
}
i++;
}
fprintf(file2,"%s", caesar);
fprintf(file2,"\n");
}
return 0;
}

最佳答案

#include <stdio.h>
#include <ctype.h>

int main (int argc, char *argv[]) {
char caesar[256];
int shift;
FILE *file1=fopen(argv[1],"r");
FILE *file2=fopen(argv[2],"w");

sscanf(argv[3], "%d", &shift);

while(fgets(caesar,sizeof(caesar), file1)!=NULL){
char ch;
int i = 0;
for(i = 0; (ch=caesar[i]) != '\0'; ++i) {
if (isalpha(ch)) {//Only alphabet
char a, z;
if(isupper(ch)){
a = 'A'; z = 'Z';
} else {
a = 'a'; z = 'z';
}
caesar[i] += shift;//this depend on the sequence of character codes.
if(caesar[i] > z){
caesar[i] = a + caesar[i] - z - 1;
}
}
}
fprintf(file2, "%s", caesar);
}
return 0;
}

关于C 语言的凯撒密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23191153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com