我尝试用c ++执行一个简单的程序,但是我无法得到那个结果我现在该怎么办我在不同平台的gcc编译器上尝试了不同版本的代码。
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int i,m,j;
char a[10],b[10],temp;
cout << " give the string " << endl;
cin >> a;
cout << a;
m=strlen(a);
j=0;
for(i=m;i>0;i--){
b[j]=a[i];
cout << " inloop "<<b;
j++;
}
cout << b << endl;
return 0;
}
答案 0 :(得分:6)
C中的所有内容均为0索引。 a[i]
在第一次迭代时为a[strlen(a)]
,即\0
。
如果您的输入为bobo
,则数组a
的内容将为
a[0] = 'b'
a[1] = 'o'
a[2] = 'b'
a[3] = 'o'
a[4] = '\0'
你的循环从[4]开始(因为strlen(a)== 4),所以你的b字符串将是:
b[0] = '\0'
b[1] = 'o'
b[2] = 'b'
b[3] = 'o'
b[4] = 'b'
打印它将导致“”被打印。
答案 1 :(得分:1)
更正您的代码。 您需要从m-1迭代到0.并在字符串
的末尾添加\ 0#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int i,m,j;
char a[10],b[10],temp;
cout << " give the string " << endl;
cin >> a;
cout << a;
m=strlen(a);
j=0;
for(i=m-1;i>=0;i--){ // Iteration changed here
b[j]=a[i];
cout << " inloop "<<b;
j++;
}
b[j] = '\0'; // Add this line
cout << endl << b << endl;
return 0;
}