(6)信息加密。编写加密程序,对用户从键盘输入的信息(不少于20个单词)以学号尾号为秘钥进行加密(例:学号尾号为3,输入信息I am z……,则密文为L dp c……,尾号为0则秘钥为10),将密文存入文本文件。
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main() {
int i,m,n;
int count;
char text[50] ;
char ptext[50];
printf("输入要加密的明文:");
gets(text);
printf("输入学号:");
scanf("%d", &m);
count = strlen(text);
n = m % 10;
if (m%10 == 0) {
n= 10;
}
for (i = 0; i < count; i++) {
if (text[i] == ' ') {
ptext[i] = ' ';
}
else {
if (text[i] >= 'a' && text[i] <= 'z' || text[i] >= 'A' && text[i] <= 'Z') {
ptext[i] = text[i] + n;
}
}
}
ptext[i] = '\0';
printf("加密后的明文为:%s", ptext);
FILE* fp;
fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("无法打开文件");
exit(0);
}
fprintf(fp, "%s", ptext);
fclose(fp);
return 0;
}
我在vs2019上进行测试 没有问题可以运行,报错的化,应该是编译器的细节问题 你试着改变一下你文件操作这里相关 : FILE* fp = NULL; 或者直接FILE* fp = fopen(...)
修改如下,供参考:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
int i,m,n;
int count;
char text[50] ;
char ptext[50];
printf("输入要加密的明文:");
gets(text);
printf("输入学号:");
scanf("%d", &m);
count = strlen(text);
if (m%10 == 0) {
n= 10;
}
else //修改
n = m % 10;
for (i = 0; i < count; i++) {
if(isupper(text[i])){ //修改
text[i] = (text[i]-'A'+ n)%26 + 'A';
}
if(islower(text[i])){ //修改
text[i] = (text[i]-'a'+ n)%26 + 'a';
}
//if (text[i] == ' ') {
// ptext[i] = ' ';
//}
//else {
//if (text[i] >= 'a' && text[i] <= 'z' || text[i] >= 'A' && text[i] <= 'Z') {
// ptext[i] = text[i] + n;
//}
//}
}
//ptext[i] = '\0'; //修改
printf("加密后的明文为:%s", text); //修改
FILE* fp;
fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("无法打开文件");
exit(0);
}
fprintf(fp, "%s", text);
fclose(fp);
return 0;
}