[英]C++ :String reversal not working?
我在理解這段代碼的輸出時遇到麻煩
#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
*/
抱歉,如果它很簡單,但我無法理解原因。 提前致謝。
確保re[0]
和re[1]
為空終止
例如,在初始化期間,您可以
for (int i = 0; i < 14; i++)
{
re[0][i] = '\0';
re[1][i] = '\0';
}
但是除此之外,我建議使用std::string
和std::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] = '\0';
}
您必須終止反轉的字符串。
您還應該#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.