如何在C ++中连接两个字符串?

时间:2013-03-10 07:13:52

标签: c++

我有一个私有类变量char name[10],我想添加.txt扩展名,以便我可以打开目录中的文件。

我该怎么做?

最好创建一个包含连接字符串的新字符串变量。

7 个答案:

答案 0 :(得分:136)

首先,请勿使用char*char[N]。使用std::string,然后其他一切变得如此简单!

实施例中,

std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!
很容易,不是吗?

现在,如果由于某种原因需要char const *,例如当你想要传递给某个功能时,那么你可以这样做:

some_c_api(s.c_str(), s.size()); 

假设此函数声明为:

some_c_api(char const *input, size_t length);

从这里开始探索std::string

希望有所帮助。

答案 1 :(得分:27)

既然是C ++,为什么不使用std::string代替char*呢? 连接将是微不足道的:

std::string str = "abc";
str += "another";

答案 2 :(得分:9)

如果您使用C编程,那么假设name确实是一个固定长度的数组,就像您说的那样,您必须执行以下操作:

char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...

您现在看到为什么每个人都推荐std::string

答案 3 :(得分:0)

strcat(destination,source)可用于在c ++中连接两个字符串。

要深入了解,您可以在以下链接中查找 -

http://www.cplusplus.com/reference/cstring/strcat/

答案 4 :(得分:0)

最好使用C ++字符串类而不是旧式C字符串,生活会容易得多。

如果您有旧样式字符串,则可以转换为字符串类

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
    string trueString = string (greeting);
    cout << trueString + "and there \n"; // compiles fine
    cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too

答案 5 :(得分:0)

C ++ 14

std::string great = "Hello"s + " World"; // concatenation easy!

回答问题:

auto fname = ""s + name + ".txt";

答案 6 :(得分:-1)

//String appending
#include <iostream>
using namespace std;

void stringconcat(char *str1, char *str2){
    while (*str1 != '\0'){
        str1++;
    }

    while(*str2 != '\0'){
        *str1 = *str2;
        str1++;
        str2++;
    }
}

int main() {
    char str1[100];
    cin.getline(str1, 100);  
    char str2[100];
    cin.getline(str2, 100);

    stringconcat(str1, str2);

    cout<<str1;
    getchar();
    return 0;
}