C ++:字符串反转不起作用?

时间:2014-08-15 12:05:17

标签: c++ string character-arrays

我无法理解我为这段代码获得的输出

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

例如

 /* 
    Input : 
    hello
    world

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

很抱歉,如果它非常基本,但我无法理解原因。提前谢谢。

3 个答案:

答案 0 :(得分:1)

确保re[0]re[1]以空值终止

例如,在初始化期间,您可以执行

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

但除此之外,我建议使用std::stringstd::reverse等。

答案 1 :(得分:1)

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

你必须终止反向字符串。

#include <string.h>函数也应该strlen()

答案 2 :(得分:0)

您忘记了数组re中字符串的终止零点。只需按以下方式定义数组

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

另请注意,您应删除标题<stdio.h>,因为它未被使用,而是包含标题<cstring>

可以使用标准算法std::reverse_copy

完成此任务

例如

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