矩形転置暗号について
Posted: 2019年9月02日(月) 12:23
平文を4行8列の暗号鍵で矩形転置で暗号化したいのですが、出力結果が画像のようになってしまいます。ソースコードのどこが間違っているのか教えてください。よろしくお願いします。
#include <iostream>
#include <fstream>
using namespace std;
#define M 4 // 矩形の行数
#define N 8 // 矩形の列数
/****************************************
メイン関数
****************************************/
void main() {
ifstream inFile; //入力ファイル
ofstream outFile; //出力ファイル
char buffer[M][N]; //文字格納のための配列
int row = 0;
int col = 0;
// 入力ファイルと出力ファイルをオープンする
inFile.open("plain.txt");
outFile.open("crypt.txt");
//入力ファイルから、最初の1文字を受け取る
char ch = inFile.get();
//ファイルの終わり(EOF)でない限り、以下を繰り返す
while (!inFile.eof()) {
buffer[row][col] = ch;
col++;
if (col == N) {
col = 0;
row++;
}
ch = inFile.get();
if (row == M) {
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
outFile << buffer[i][j];
buffer[i][j] = 0;
}
col = 0;
row = 0;
}
}
}
//ファイルを閉じる
inFile.close();
outFile.close();
}
これはどうやって判断しましたか。
m the Sp/irit rov/er#*on T/uesday s/howing gray rocks
m the Sp
irit rov
er#*on T
uesday s
mieu/ res/ti#s/ht*d/e oa/ roy/So /pvTs
#include <iostream>
#include <fstream>
using namespace std;
#define M 4
#define N 8
void main() {
ifstream inFile;
ofstream outFile;
char buffer[M][N];
int row = 0;
int col = 0;
inFile.open("plain.txt");
outFile.open("crypt.txt");
char ch = inFile.get();
while (!inFile.eof()) {
buffer[row][col] = ch;
col++;
if (col == N) {
col = 0;
row++;
}
ch = inFile.get();
if (row == M) {
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
outFile << buffer[i][j];
buffer[i][j] = 0;
}
col = 0;
row = 0;
}
}
}
inFile.close();
outFile.close();
}
inFile.close() の前に次のコードを追加すればよいのではありませんか?
if (col != 0 || row != 0) {
while (1) {
buffer[row][col] = ' ';
if (++col == N) {
col = 0;
if (++row == M) break;
}
}
for (int j = 0; j < N; j++)
for (int i = 0; i < M; i++) outFile << buffer[i][j];
}