我有以下代码,并希望得到一个字符,例如:“你好,你好吗?” (这只是我想要实现的一个例子)
如何连接 2 个字符数组并在中间添加“,”和“你”?在最后?
到目前为止,这连接了 2 个数组,但不确定如何将其他字符添加到我想要提出的最终 char 变量中。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char foo[] = { "hello" };
char test[] = { "how are" };
strncat_s(foo, test, 12);
cout << foo;
return 0;
}
编辑:
这是我在您的所有回复后想出的。我想知道这是否是最好的方法?
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char foo[] = { "hola" };
char test[] = { "test" };
string foos, tests;
foos = string(foo);
tests = string(test);
string concat = foos + " " + tests;
cout << concat;
return 0;
}
原文由 Matimont 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 C++ 中,使用
std::string
和operator+
,它是专门为解决此类问题而设计的。