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;
}
编辑:
这是我在你的所有回复之后提出的.我想知道这是否是最佳方法?
#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;
}
qua*_*dev 11
在C++中,使用std::string和operator+,它专门用于解决这样的问题.
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string foo( "hello" );
    string test( "how are" );
    cout << foo + " , " + test;
    return 0;
}
最好的办法是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);
| 归档时间: | 
 | 
| 查看次数: | 57412 次 | 
| 最近记录: |