如何在一行上连接多个C++字符串?

191

C#有一个语法特性,允许您在一行上将多个数据类型连接在一起。

string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;

在C++中该怎么做呢?据我所见,你需要将它们分别放在不同的行上完成操作,因为它不支持使用+运算符连接多个字符串/变量。这样做是可以的,但看起来不太整洁。

string s;
s += "Hello world, " + "nice to see you, " + "or not.";

以上代码会产生一个错误。


7
如前所述,这并不是因为“它不支持使用+运算符添加多个字符串/变量”,而是因为您正在尝试将char *指针相加。这就是导致错误的原因 - 因为对指针求和是没有意义的。如下所述,将至少第一个操作数转换为std::string,就不会出现错误了。 - underscore_d
1
产生了哪个错误? - Wolf
可能是如何连接std :: string和int?的重复问题。 - vitaut
25个回答

0

你也可以“扩展”字符串类并选择你喜欢的运算符(<<,&,|等)

这里是使用operator<<的代码,以显示与流没有冲突

注意:如果取消注释s1.reserve(30),则只有3个new()操作请求(1个用于s1,1个用于s2,1个用于reserve;不幸的是您不能在构造函数时间保留);如果不保留,则s1必须在增长时请求更多内存,因此它取决于您的编译器实现增长因子(在此示例中我的增长因子似乎为1.5,因此有5个new()调用)

namespace perso {
class string:public std::string {
public:
    string(): std::string(){}

    template<typename T>
    string(const T v): std::string(v) {}

    template<typename T>
    string& operator<<(const T s){
        *this+=s;
        return *this;
    }
};
}

using namespace std;

int main()
{
    using string = perso::string;
    string s1, s2="she";
    //s1.reserve(30);
    s1 << "no " << "sunshine when " << s2 << '\'' << 's' << " gone";
    cout << "Aint't "<< s1 << " ..." <<  endl;

    return 0;
}

0

使用lambda函数的简单预处理器宏和stringstream看起来很不错:

#include <sstream>
#define make_string(args) []{std::stringstream ss; ss << args; return ss;}() 

然后

auto str = make_string("hello" << " there" << 10 << '$');

0
一行:
std::string s = std::string("Hello world, ") + std::to_string(888) + " nice to see you";

或者

std::string s = std::string() + "Hello world, " + std::to_string(888) + " nice to see you";

-1
这对我有效:
#include <iostream>

using namespace std;

#define CONCAT2(a,b)     string(a)+string(b)
#define CONCAT3(a,b,c)   string(a)+string(b)+string(c)
#define CONCAT4(a,b,c,d) string(a)+string(b)+string(c)+string(d)

#define HOMEDIR "c:\\example"

int main()
{

    const char* filename = "myfile";

    string path = CONCAT4(HOMEDIR,"\\",filename,".txt");

    cout << path;
    return 0;
}

输出:

c:\example\myfile.txt

12
每当有人将宏用于比代码保护或常量更复杂的事情时,一只小猫咪就会哭泣 :P - Rui Marques
1
除了不高兴的小猫之外:为每个参数创建一个字符串对象是不必要的。 - SebastianK
2
因为使用宏绝对是一个不好的解决方案,所以被踩了。 - dhaumann
这甚至让我对C都感到恐惧,但在C++中,它是魔鬼般的。@RuiMarques:在哪些情况下,宏比const更适合用于常量(如果需要零存储,则使用enum)? - underscore_d
@underscore_d 绝对不正确。看看 Boost.Preprocessor 或 Boost.Config 就知道为什么了;有些事情如果没有宏是无法在语言中完成的。 - Alice
显示剩余8条评论

-1
你有尝试避免使用 += 吗? 可以尝试使用 var = var + ... 的方式 这对我很有效。
#include <iostream.h> // for string

string myName = "";
int _age = 30;
myName = myName + "Vincent" + "Thorpe" + 30 + " " + 2019;

我使用C++ Borland Builder 6,对我来说它很好用。不要忘记包含这些头文件: #include <iostream.h> // string #include <system.hpp> // ansiString - vincent thorpe
+= 对于这种情况没有重载,似乎您认为正在添加数字而不是连接字符串。 - vincent thorpe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接