c++loopscharnested-loopsstdstring

Getting random symbols after trying to replace chars in C++


I'm trying to replace every letter in string to next letter (a -> b, c -> d, etc.).

I get random symbols or XXXX after compiling and running the program.

#include <iostream>
#include <string>

using namespace std;
int main(){
    char arr1[26] = {'a', 'b', 'c', 'd',
                       'e', 'f', 'g', 'h',
                       'i', 'j', 'k', 'l',
                       'm', 'n', 'o', 'p',
                       'q', 'r', 's', 't',
                       'u', 'v', 'w', 'x',
                       'y', 'z'};
    string x;
    getline(cin, x);
    for(int i = 0; i < x.length(); i++){
        for(int h = 0; h < 26; h++){
            if(x[i] == arr1[h]){
                x[i] = arr1[h + 1];
            }
        }
    }
    cout << x;
    return 0;
}

I think I'm doing something wrong with char datatype.


Solution

  • You have two issues with your code. Firstly, if h == 25, then h+1 is 26, and there is no arr1[26]. This is where the "random symbols" are coming from.

    The second issue, is that once you've replaced the character, you still check it again, and it finds another match and replaces it, and then rechecks (etc.).

    You can change your if statement like so:

    if(x[i] == arr1[h]){
         x[i] = arr1[(h + 1) % 26]; // in case h + 1 > 26, loop back to 0 (i.e. 'a')
         break; // don't keep searching for another match
    }
    

    You can change how you handle the value when h == 25 however you'd like, I just rolled around to 0 for simplicity.