【发布时间】:2014-08-06 22:46:08
【问题描述】:
我有以下代码,希望得到一个字符,例如:“你好,你好吗?” (这只是我想要实现的一个例子)
如何连接 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;
}
【问题讨论】:
-
使用
std::string。它甚至比您尝试使用数组更容易(这根本不起作用,因为数组具有固定大小)。 -
不相关:您正在调用
#include <string>,但对 std::string(s) 没有执行任何操作。如果您正在操作 C 风格的字符串,您可能至少应该包括#include <cstring>。更好的解决方案可能是将输入转换为 std::string 类型,如果某些函数需要 c-string,请在 std::string 上调用.c_str方法。 -
为什么你的 stringx 周围有大括号
-
您使用
char的数组来表示您的字符串有什么原因吗? -
顺便说一句 - 在输出后输出
'\n'是个好主意 - 在某些系统上,除非发送最后的换行符,否则在程序退出后文本可能不可见(例如,某些 UNIX/Linux shells - 假设每个程序都会用换行符结束每一行 - 清除回行首然后打印提示符)。
标签: c++ arrays char concatenation