如何通过组合多个字符数组来创建字符数组?

How can i creat a char array by combine multiple char arrays?

本文关键字:字符 数组 创建 何通过 组合      更新时间:2023-10-16

如何在 c++ 中将两个字符数组组合成一个字符数组?

我认为应该是这样的:

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

输出将是:

12345,678/n

我想通过串行端口发送一个字符数组,并且想知道如何做到这一点。

既然你指定了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 分配足够的空间。这可能会导致内存损坏。

在 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;
}

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

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