{ {"2020B200301","刘滨","男",18,{2020,9,20},70,85}, {"2020B200302","阚美娟","女",17,{2020,9,20},87,95}, {"2020B200303","胡大勇","男",17,{2020,9,20},69,80}, {"2020B200305","黎丽","女",18,{2020,9,20},68,88}, {"2020B200309","金鑫","男",19,{2019,9,1},90,85} }将上题的成绩加密保存,当读出数据,密码不对成绩显示**号。(密钥由字母构成)
时间: 2023-07-19 08:21:22 浏览: 68
下面是将成绩加密保存、读取时解密并打印的示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
// 定义学生结构体
struct Student {
char id[20]; // 学号
char name[20]; // 姓名
char gender[5]; // 性别
int age; // 年龄
int enroll_date[3]; // 入学日期,第一个元素为年份,第二个元素为月份,第三个元素为日期
char encrypted_grade[20]; // 加密后的成绩
};
// 加密函数
void encrypt(char* str, char* key) {
int str_len = strlen(str);
int key_len = strlen(key);
for (int i = 0; i < str_len; i++) {
str[i] = str[i] ^ key[i % key_len]; // 逐个字符异或密钥
}
}
// 解密函数
void decrypt(char* str, char* key) {
int str_len = strlen(str);
int key_len = strlen(key);
for (int i = 0; i < str_len; i++) {
str[i] = str[i] ^ key[i % key_len]; // 逐个字符异或密钥
}
}
int main() {
// 定义密钥
char key[] = "password";
// 定义学生数组
Student students[] = {
{"2020B200301", "刘滨", "男", 18, {2020, 9, 20}, "", ""},
{"2020B200302", "阚美娟", "女", 17, {2020, 9, 20}, "", ""},
{"2020B200303", "胡大勇", "男", 17, {2020, 9, 20}, "", ""},
{"2020B200305", "黎丽", "女", 18, {2020, 9, 20}, "", ""},
{"2020B200309", "金鑫", "男", 19, {2019, 9, 1}, "", ""}
};
// 加密保存成绩
for (int i = 0; i < 5; i++) {
int grade1, grade2;
cout << "请输入" << students[i].name << "的两门成绩(用空格分隔):";
cin >> grade1 >> grade2;
sprintf(students[i].encrypted_grade, "%d %d", grade1, grade2); // 将成绩转换为字符串并保存
encrypt(students[i].encrypted_grade, key); // 加密成绩
}
// 读取并解密成绩
for (int i = 0; i < 5; i++) {
decrypt(students[i].encrypted_grade, key); // 解密成绩
int grade1, grade2;
sscanf(students[i].encrypted_grade, "%d %d", &grade1, &grade2); // 从字符串中读取成绩
if (strcmp(key, "password") != 0) { // 如果密钥不正确,成绩显示为**
cout << students[i].name << "的成绩:**" << endl;
} else {
cout << students[i].name << "的成绩:" << grade1 << ", " << grade2 << endl;
}
}
return 0;
}
```
在这个示例代码中,我们定义了一个 `encrypt` 函数和一个 `decrypt` 函数,分别用于加密和解密字符串。在加密时,我们逐个字符与密钥进行异或操作;在解密时,我们也逐个字符与密钥进行异或操作,从而得到原始字符串。
对于每个学生的成绩,我们先将两门成绩转换为字符串并保存在 `encrypted_grade` 字段中,然后调用 `encrypt` 函数对其进行加密。在读取成绩时,我们先调用 `decrypt` 函数对 `encrypted_grade` 字段进行解密,然后从解密后的字符串中读取成绩。如果密钥不正确,我们就将成绩显示为 **。
阅读全文