C++ C++;:字符串反转不工作?
我很难理解这段代码的输出C++ C++;:字符串反转不工作?,c++,string,character-arrays,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],
#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;
}
#包括
#包括
使用名称空间std;
int main(){
int i=0;
int j=0;
int k=0;
char ch[2][14];
char-re[2][14];
不能确保re[0]
和re[1]
以null结尾
例如,在初始化期间,您可以执行以下操作
for (int i = 0; i < 14; i++)
{
re[0][i] = '\0';
re[1][i] = '\0';
}
for(int i=0;i<14;i++)
{
re[0][i]='\0';
re[1][i]='\0';
}
但除此之外,我建议使用std::string
和std::reverse
等等。用于(I=0;I<2;I++)
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';
}
{
int len=strlen(ch[i]);
对于(j=0,k=len-1;j
您必须终止反向字符串
另外,您还应该为strlen()
函数包含。您忘记了数组中字符串的终止零re
只需按以下方式定义数组
char ch[2][14] , re[2][14] = {};
^^^^
还要考虑到您应该删除标题
,因为它没有被使用,而是包含标题
使用标准算法std::reverse\u copy
比如说
/*
Input :
hello
world
Output :
olleh<some garbage value>dlrow
dlrow
*/
#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;
}
#包括
#包括
#包括
int main()
{
常数大小N=2;
常数大小M=14;
char ch[N][M]={};
字符re[N][M]={};
std::cout您应该使用。您还应该避免反转字符串。在许多情况下,按字节反转字符串(这就是std::reverse
将要完成的,也是您在这里尝试的)例如,在处理UTF-8数据时,将产生非常意外和不正确的结果。您忘了终止strings@mch谢谢。它帮助了你,并且尽量避免在你的C++代码中包括STDIO。……如果需要的话,使用CSTDIO。