[英]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 确保
re[0]
和re[1]
为空终止
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. 但是除此之外,我建议使用
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';
}
you have to terminate your reversed strings. 您必须终止反转的字符串。
also you should #include <string.h>
for the strlen()
function. 您还应该
#include <string.h>
作为strlen()
函数。
You forgot about the terminating zero for strings in array re
Simply define the array the following way 您忘记了数组
re
字符串的终止零,只需按以下方式定义数组
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>
. 还应考虑到应该删除标头
<stdio.h>
因为它没有使用,而应包含标头<cstring>
。
This task can be done with using standard algorithm std::reverse_copy
可以使用标准算法
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.