如何在C ++中连接两个字符串? [英] How to concatenate two strings in C++?
问题描述
我有一个私有类变量(char name [10]),我想添加.txt扩展名,以便我可以打开目录中的文件。我该怎么办?最好创建一个包含连接字符串的新字符串变量。
I have a private class variable (char name[10]) to which I would like to add the .txt extension so that I can open the file present in the directory. How do I go about this? It would be preferable to create a new string variable that holds the concatenated string.
推荐答案
首先, code> char * 或 char [N]
。使用 std :: string
,那么一切变得如此简单!
First of all, don't use char*
or char[N]
. Use std::string
, then everything else becomes so easy!
示例,
std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!
很容易,不是吗?
现在如果你需要 char const *
某些原因,比如当你想传递给某些函数时,那么你可以这样做:
Now if you need char const *
for some reason, such as when you want to pass to some function, then you can do this:
some_c_api(s.c_str(), s.size());
假设此函数声明为:
some_c_api(char const *input, size_t length);
探索 std :: string
这里:
- Documentation of std::string
希望有帮助。
这篇关于如何在C ++中连接两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!