Samed Škulj
Samed Škulj

Reputation: 29

C++ - Decrypting a string from file

As you can see from the title I need to decrypt the strings in a text file. I have major problems with this so if you can help me I would really appreciate it.

First of all, here is the input file:

saoreecessinntfi
pmrrj ie2
borj

I want to decrypt these words like this:

sesnaestocifreni
primjer 2
broj

I have used the matrix 4x4 to do this, and here is the code so far:

#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;
}

Here is the output:

sesnaestocifreni

It only outputs the first word in text file. I think the problem with this is that I do not know how "long" is "i" and "j" in those other words beacuse the first word has 16 charachters so the counter "i" and "j" are set on 4. How to count each words charachters and if they are the same then decrpyt the word. Also if the word is right spelled I need to cout in the program "ERROR". For example

apple

I do not need to decrypt this word, beacuse it is right word, and "i" and "j" would not be the same or I do not know what I am talking about.

Upvotes: 0

Views: 93

Answers (2)

Botje
Botje

Reputation: 30830

If I understand your problem correctly, you are given a line of n*n characters and need to unscramble it as given.

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;
}

Upvotes: 1

brc-dd
brc-dd

Reputation: 12964

I think this should work just the fine for your case:

#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;
}

Sample test.txt file:

saoreecessinntfi
pmrrj ie2
borj
apple

Output on test run:

sesnaestocifreni
primjer 2
broj
ERROR

Upvotes: 1

Related Questions