gpt4 book ai didi

c++ - 在 C++ 中连接 char 数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:15 25 4
gpt4 key购买 nike

我有以下代码,并希望以一个字符结尾,例如:“你好,你好吗?” (这只是我想要实现的一个例子)

如何连接 2 个字符数组并在中间添加“,”和“you?”最后呢?

到目前为止,这连接了 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;
}

最佳答案

在 C++ 中,使用 std::stringoperator+,它是专门为解决此类问题而设计的。

#include <iostream>
#include <string>
using namespace std;

int main()
{
string foo( "hello" );
string test( "how are" );
cout << foo + " , " + test;
return 0;
}

关于c++ - 在 C++ 中连接 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24255051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com