-1

I'm trying to solve a puzzle from beecrowd (fka uri online judge), where i have to "encrypt" a message (puzzle 1024 - encryption). I have not implemented the full cryptography yet, as I am just trying to manipulate the string in a simple way first, but I am not succeeding at it, and I don't understand why.

Here's what I'm trying to do: replace any non-alphabetical character (lowercase) with an X. I am storing all words at the array of strings words[], dynamically allocated.

input:
    5
    Texto #3
    abcABC1
    vxpdylY .ph
    vv.xwfxo.fd
    nothingtoreplace

expected output:
    XestoXXX
    abcXXXX
    vxpdulXXXph
    vvXxwfxoXfd
    nothingtoreplace

The problem is that when I try to replace the characters, it "deletes" part of the string:

  • words[i][j] = "X"; -> with this method, if the char I want to replace is in the first position of the string, it replaces the whole string with "X", and if it is in the middle, it doesn't replace. The output I get is:
X
abcABC1
vxpdylY .ph
vv.xwfxo.fd
nothingtoreplace
  • words[i]->replace(j,j,(string)"X"); -> using this method, it puts an extra "X" if the first char is to be replaced, and for any characters in the middle, it replaces them and cuts out part of the string (2 or 3 last characters), with the following output:
XXextoX
abcXX
vxpdylX
vvXwfxoX
nothingtoreplace

I don't know any other method to do it, and I am trying to improve at c++, so if anyone know what is going wrong, it would really help me here. Here's the full code:

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::string;

int main() {

    unsigned int n, i, j; cin >> n;
    string** words = new string*[n+1];
    for(i=0; i<=n; i++) words[i] = new string[1001];
    for(i=0; i<=n; i++) std::getline(cin, *words[i]);

    for(i=0; i<=n; i++){
        for(j=0; j < words[i]->size(); j++){ //either size() or length() functions have the same effect
            if (words[i]->at(j) < 'a' || words[i]->at(j) > 'z'){
                //words[i][j] = "X";
                words[i]->replace(j,j,(string)"X");
                //this method has the same effect as the above:
                //words[i]->erase(j,j);
                //words[i]->insert(j,"#");
            }
        }
    }

    for(i=0; i<=n; i++) cout << *words[i] << '\n';

    for(i=0; i<n; i++) delete words[i];
    delete words;
    return 0;

}
  • 1
    Your problem might be that `"X"` is a string literal, while `'X'` (single quotes) is a character. – BoP May 30 '22 at 13:37
  • I would also have used `std::vector>` and skipped all the new and delete. Among other things, this saves you from that the `delete` ought to be `delete[]` for deleting arrays. – BoP May 30 '22 at 13:42

0 Answers0