用C++连接char数组

Mat*_*ont 6 c++ arrays concatenation char

我有以下代码,并希望最终得到一个字母,如:"你好,你好吗?" (这只是我想要实现的一个例子)

如何连接2个char数组并在中间添加","和"你?" 在末尾?

到目前为止,这连接了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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

这是我在你的所有回复之后提出的.我想知道这是否是最佳方法?

#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;
}
Run Code Online (Sandbox Code Playgroud)

qua*_*dev 11

在C++中,使用std::stringoperator+,它专门用于解决这样的问题.

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

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

  • 这种方法的问题是使用字符串,我需要连接2个字符 (2认同)

Nay*_*iya 5

最好的办法是std::string在C ++中用作其他答案。如果您真的需要使用char,请尝试这种方式。没有测试。

const char* foo = "hello";
const char* test= "how are";

char* full_text;
full_text= malloc(strlen(foo)+strlen(test)+1); 
strcpy(full_text, foo ); 
strcat(full_text, test);
Run Code Online (Sandbox Code Playgroud)

  • 因为它确实 - 最初的 C++ 代码被转换为 C。但是对于新代码,你应该使用 `new`。当您拥有 C++ 的所有额外能力时,为什么还要生成 C 代码 (3认同)
  • 为什么在C ++代码中使用`malloc`?你也忘了留空字符 (2认同)