C中的凯撒密码

时间:2014-04-21 05:08:36

标签: c arrays encryption shift

在这个caesars密码中我如何制作它以便它读取空格,特殊字符(!@#* * ...)和数字并保持它们原样并打印出来?另外我在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;
}

1 个答案:

答案 0 :(得分: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;
}