【问题标题】:why is my string ( char array ) is not printing? [closed]为什么我的字符串(字符数组)没有打印? [关闭]
【发布时间】:2014-02-21 10:10:15
【问题描述】:

我尝试在 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;

}

【问题讨论】:

  • 目前没有机会得到这个问题的答案,因为你没有说出你想要的结果是什么,而且心灵感应很难。
  • 您似乎正在尝试反转字符串。使用std::string,它具有字符串操作所需的所有功能。
  • “我无法得到那个结果”——我们不是算命先生。告诉我们预期结果和实际结果,以及您提供的输入。
  • 有理由不使用 C++ 字符串吗?
  • @Mahesh 知道为什么在阅读您的评论时我会想到回形针的图像吗?

标签: c++ arrays char


【解决方案1】:

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'

您的循环从 a[4] 开始(因为 strlen(a) == 4),所以您的 b 字符串将是:

b[0] = '\0'
b[1] = 'o'
b[2] = 'b'
b[3] = 'o'
b[4] = 'b'

打印它会导致 "" 被打印出来。

【讨论】:

    【解决方案2】:

    更正您的代码。 您需要从 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;
    }
    

    【讨论】:

    • 谢谢它的工作,但为什么我不能只使用 cout b (对不起,我把这个评论从手机)
    • @user2253623 你可以做到。问题出在 for 语句中。您正在将 '\0' 复制到 b[0] 中。 '\0' 是字符串终止符。
    猜你喜欢
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2020-03-15
    • 2023-02-15
    • 1970-01-01
    相关资源
    最近更新 更多