我有以下代码,想要得到一个字符串,比如:"你好,你怎么样?"(这只是我尝试实现的示例)
我应该如何将这2个字符数组连接起来,并在中间添加“,”和结尾处添加“you?”呢?
到目前为止,这个代码可以将这两个数组连接起来,但我不确定如何将额外的字符添加到我想要生成的最终字符变量中。
#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;
}
std::string
。它比你使用数组的尝试更容易(因为数组具有固定大小,所以根本无法工作)。 - ghostofstandardspast#include <string>
,但未对 std::string 进行任何操作。如果您正在操作 C 风格的字符串,那么您可能至少应该包含#include <cstring>
。但更好的解决方案可能是将输入转换为 std::string 类型,如果某些函数需要 c 字符串,则在您的 std::string 上调用.c_str
方法。 - DavidO'\n'
- 在某些系统中,如果没有发送最后的换行符,则程序退出后可能不会显示文本(例如某些UNIX / Linux shell - 假设每个程序都会在每行末尾添加一个换行符 - 清除回到行首然后打印提示)。 - Tony Delroychar* f; char* b; std::string c; c.reserve(strlen(f) + strlen(b) + 2); ((c += f) += ' ') += b;
,即直接将 C 字符串分配给 std::string,而不是产生额外的副本(foos/tests!),并且预留足够的内存可以避免 std::string 中的重新分配。 - Aconcagua