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

C++ :String reversal not working?

本文关键字:不起作用 字符串 C++      更新时间:2023-10-16

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

#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 stringn";
    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
  */

对不起,如果它很基本,但我不明白原因。提前谢谢。

确保 re[0]re[1] 以 null 结尾

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

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

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

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

你必须终止你的反转字符串。

此外,您还应该#include <string.h> strlen()功能。

您忘记了数组 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;
}