连接C ++中的char数组 [英] Concatenate char arrays in C++

查看:107
本文介绍了连接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个字符数组,并在中间加上,"和"you"?最后呢?

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::stringoperator+专门解决此类问题.

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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆