C++ - 从文件解密字符串



正如你从标题中看到的,我需要解密文本文件中的字符串。我对此有很大的问题,所以如果你能帮助我,我将不胜感激。

首先,这里是输入文件:

saoreecessinntfi
pmrrj ie2
borj

我想像这样解密这些词:

sesnaestocifreni
primjer 2
broj

我已经使用矩阵 4x4 来执行此操作,这是到目前为止的代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() 
{
ifstream test;
test.open("test.txt");
char word[5][5];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
test >> word[i][j];
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << word[j][i];
}
}   

return 0;
}

这是输出:

sesnaestocifreni

它只输出文本文件中的第一个单词。我认为这样做的问题是我不知道其他单词中的"i"和"j"有多长,因为第一个单词有 16 个字符,所以计数器"i"和"j"设置为 4。如何计算每个单词的字符,如果它们相同,则对单词进行解码。此外,如果单词拼写正确,我需要在程序"错误"中 cout。例如

apple

我不需要解密这个词,因为它是正确的词,"i"和"j"不会相同,或者我不知道我在说什么。

我认为这应该适合您的情况:

#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
int matrixSize(std::string &str) {
auto x = sqrt(str.length());
return x - floor(x) == 0 ? x : 0;
}
int main() {
std::fstream file("test.txt");
std::string str;
while (std::getline(file, str)) {
if (int n = matrixSize(str)) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout << str.at(j * n + i);
std::cout << std::endl;
} else
std::cout << "ERROR" << std::endl;
}
return 0;
}

示例test.txt文件:

saoreecessinntfi
pmrrj ie2
borj
apple

测试运行时的输出:

sesnaestocifreni
primjer 2
broj
ERROR

如果我正确理解您的问题,您将获得一行 n*n 个字符,并且需要按照给定的方式对其进行解密。

while (true) {
std::string line;
std::getline(cin, line);
if (line.empty())
break;
int n = 1;
while (n*n < line.size()) {
n++;
}
if (n*n != line.size()) {
std::cout << "ERROR" << std::endl;
continue;
}
std::string unscrambled;
for (int col = 0; col < n; col++)
for (int row = 0; row < n; row++)
unscrambled.append(1, line[row * n + col]);
std::cout << unscrambled << std::endl;
}

最新更新