如何通过组合多个字符数组来创建字符数组?
How can i creat a char array by combine multiple char arrays?
如何在 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();
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?