c++stringcharacter-arrays

C++ :String reversal not working?


I am having trouble understanding the output I am getting for this piece of code

#include<iostream>
#include<stdio.h>

using namespace std;

int main() {
    int i = 0;
    int j = 0;
    int k = 0;

    char ch[2][14];
    char re[2][14];

    cout << "\nEnter 1st string \n";
    cin.getline(ch[0], 14);

    cout << "\nEnter the 2nd string\n";
    cin.getline(ch[1], 14);

    for(i = 0; i < 2; i++) {
        int len = strlen(ch[i]);
        for(j = 0, k = len - 1; j < len; j++, k--) {
            re[i][j]=ch[i][k];
        }
    }
    cout << "\nReversed strings are \n";
    cout << re[0];
    cout << endl << re[1] << endl;
    return 0;
}

for example

 /* 
    Input : 
    hello
    world

    Output :
    olleh<some garbage value>dlrow
    dlrow
  */

Sorry if it very basic, but I can't understand the reason. Thanks in advance.


Solution

  • You forgot about the terminating zero for strings in array re Simply define the array the following way

    char ch[2][14] , re[2][14] = {};
                               ^^^^
    

    Also take into account that you should remove header <stdio.h> because it is not used and instead of it include header <cstring>.

    This task can be done with using standard algorithm std::reverse_copy

    For example

    #include <iostream>
    #include <algorithm>
    #include <cstring>
    
    int main() 
    {
        const size_t N = 2;
        const size_t M = 14;
    
        char ch[N][M] = {};
        char re[N][M] = {};
    
        std::cout << "\nEnter 1st string: ";
        std::cin.getline( ch[0], M );
    
        std::cout << "\nEnter the 2nd string: ";
        std::cin.getline( ch[1], M );
    
        std::cout << std::endl;
    
        for ( size_t i = 0; i < N; i++ )
        {
            std::reverse_copy( ch[i], ch[i] + std::strlen( ch[i] ) , re[i] );
        }
    
        for ( const auto &s : re ) std::cout << s << std::endl;
    
        return 0;
    }