#include <iostream> using namespace std; #define STR_LEN 80 #define MAX_LINE 20 //读入一行,长度不超过maxLength void readLine(char str[], int maxLength) { int i = 0; while (i < maxLength) { char ch = cin.get(); if (ch != '\n') { str[i] = ch; } else { break; } i++; } str[i] = '\0'; } void caesarEncrypt(char plainText[][STR_LEN + 1], char cipherText[][STR_LEN + 1], int key) { int a = 0; while (cipherText[a][0] != '#') { a = a + 1; } for (int j = 0; j < a; j++) { int i = 0; while (cipherText[j][i] != '\0') { if (isalpha(cipherText[j][i])) { plainText[j][i] = ((cipherText[j][i] + key - 'A') % 26) + 'A'; } else { plainText[j][i] = cipherText[j][i]; } i++; } } } int main() { char cipherText[MAX_LINE][STR_LEN + 1]; //存储密文 char plainText[MAX_LINE][STR_LEN + 1]; int key; //输入明文 readLine(cipherText[0], STR_LEN); //输入密钥 cin >> key; //按密钥进行恺撒加密 caesarEncrypt(plainText, cipherText, key); //输出密文 for (int i = 0; i < MAX_LINE; i++) { for(int j=0 ; j<STR_LEN; j++) { if (plainText[i][0] == '\0') { break; } cout << plainText[j][i]; } } return 0; }这个代码哪里有问题
时间: 2024-01-11 20:03:22 浏览: 123
使用include <iostream>时一定要加using namespace std
这份代码有几个问题:
1.在`caesarEncrypt`函数中,应该将密文的内容赋给明文而不是将明文的内容赋给密文。
2.在输出密文时,应该按照行列的顺序输出,而不是按列行的顺序输出。
3.在输出密文时,应该判断明文是否为空,如果为空就跳出循环,否则会输出一些奇怪的字符。
下面是修改后的代码:
```C++
#include <iostream>
using namespace std;
#define STR_LEN 80
#define MAX_LINE 20
//读入一行,长度不超过maxLength
void readLine(char str[], int maxLength) {
int i = 0;
while (i < maxLength) {
char ch = cin.get();
if (ch != '\n') {
str[i] = ch;
} else {
break;
}
i++;
}
str[i] = '\0';
}
void caesarEncrypt(char plainText[][STR_LEN + 1], char cipherText[][STR_LEN + 1], int key) {
int a = 0;
while (cipherText[a][0] != '#') {
a = a + 1;
}
for (int j = 0; j < a; j++) {
int i = 0;
while (cipherText[j][i] != '\0') {
if (isalpha(cipherText[j][i])) {
plainText[j][i] = ((cipherText[j][i] - 'A' + key) % 26) + 'A';
} else {
plainText[j][i] = cipherText[j][i];
}
i++;
}
plainText[j][i] = '\0';
}
}
int main() {
char cipherText[MAX_LINE][STR_LEN + 1]; //存储密文
char plainText[MAX_LINE][STR_LEN + 1];
int key;
//输入密文
for (int i = 0; i < MAX_LINE; i++) {
readLine(cipherText[i], STR_LEN);
if (cipherText[i][0] == '#') {
break;
}
}
//输入密钥
cin >> key;
//按密钥进行恺撒加密
caesarEncrypt(plainText, cipherText, key);
//输出密文
for (int i = 0; i < MAX_LINE; i++) {
if (plainText[i][0] == '\0') {
break;
}
for (int j = 0; plainText[i][j] != '\0'; j++) {
cout << plainText[i][j];
}
cout << endl;
}
return 0;
}
```
阅读全文