简体   繁体   中英

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.

Make sure that re[0] and re[1] are null-terminated

For example during initialization you could do

for (int i = 0; i < 14; i++)
{
    re[0][i] = '\0';
    re[1][i] = '\0';
}

But aside from that I suggest to used std::string and std::reverse and the like.

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];
    }
    re[i][len] = '\0';
}

you have to terminate your reversed strings.

also you should #include <string.h> for the strlen() function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM