【问题标题】:How can i creat a char array by combine multiple char arrays? [closed]如何通过组合多个 char 数组来创建 char 数组? [关闭]
【发布时间】:2019-11-26 18:00:40
【问题描述】:

如何在 C++ 中将两个 char 数组合并为一个 char 数组?

我认为应该是这样的:

char[5] text1 = "12345";
char[1] text2 = ",";
char[5] text2 = "678/n";

char[] Value = text1 + text2 + text3;

输出将是:

12345,678/n

我想通过串口发送一个 char 数组,想知道我该怎么做。

【问题讨论】:

  • c++ 你应该考虑使用std::string - 更容易搞砸。
  • 在这里绝对同意阿德里安的观点。 C++ 提供了一个“包含电池”string 类型,它可以轻松完成所有这些事情。使用该类型而不是字符数组,这不过是麻烦。
  • 您可以使用strcat,但将多个字符串连接在一起并不是最有效的方法。
  • 好吧,为了说明我所说的“除了麻烦”是什么意思,在上面的源代码中,char[5] 有五个字符,因此没有“终止空字节”。标准的“C”函数会因此而发牢骚……非常糟糕。而std::string 会做你想做的事。 (“C”语言发生过的最好的事情是......“++”!)
  • 字符值[] = "12345" "," "678/n";

标签: c++ arrays char


【解决方案1】:

既然你指定了C++,那肯定用std::string:

std::string text1 = "12345";
std::string text2 = ",";
std::string text3 = "678/n";

std::string Value = text1 + text2 + text3;

如果您需要访问要发送到串行端口的实际字符,请使用Value.c_str() 访问它们

顺便说一句,您的原始代码没有为 char 数组中的尾随 null 分配足够的空间。这可能会导致内存损坏。

【讨论】:

    【解决方案2】:

    在 C++ 中使用std::string。它专门为解决此类问题而创建。

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string text1( "12345" );
        string text2( "," );
        string text3( "678/n" );
        cout << text1 + text2 + text3;
        return 0;
    }
    

    但是,如果您想要使用char 数组的答案,您可以试试这个。

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main()
    {
        char text1[6] = "12345";
        char text2[2] = ",";
        char text3[6] = "678/n";
    
        char combine[100];
    
        strcpy(combine, text1); 
    
        strcat(combine, text2);
        strcat(combine, text3);
    
        puts(combine);
    
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      在 C++ 中,您可以使用字符串流:

      stringstream ss;
      ss << "12345" << "," << "678/n";
      cout << ss.str();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-25
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        • 2018-10-23
        • 2013-01-03
        相关资源
        最近更新 更多