Concatenate char arrays in C++(在 C++ 中连接 char 数组)
问题描述
我有以下代码,希望得到一个字符,例如:你好,你好吗?"(这只是我想要实现的一个例子)
I have the following code and would like to end up with a char such as: "Hello, how are you?" (this is just an example of what I'm trying to achieve)
如何连接 2 个字符数组并在中间添加,"和你"?最后?
How can I concatenate the 2 char arrays plus adding the "," in the middle and the "you?" at the end?
到目前为止,这连接了 2 个数组,但不确定如何将其他字符添加到我想要提出的最终 char 变量中.
So far this concatenates the 2 arrays but not sure how to add the additional characters to my final char variable I want to come up with.
#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;
}
这是我在收到您的所有回复后得出的结论.我想知道这是否是最好的方法?
This is what I came up with after all your replies. I'd like to know if this is the best approach?
#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::string
,和operator+
,专门用来解决这样的问题.
In C++, use std::string
, and the operator+
, it is designed specifically to solve problems like this.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string foo( "hello" );
string test( "how are" );
cout << foo + " , " + test;
return 0;
}
这篇关于在 C++ 中连接 char 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中连接 char 数组
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01