如何从字符串文字的串联中形成C ++字符串?

| 我想将字符串文字和整数连接起来,像这样:
string message(\"That value should be between \" + MIN_VALUE + \" and \" + MAX_VALUE);
但这给了我这个错误:
error: invalid operands of types ‘const char*’ and ‘const char [6]’ to binary ‘operator+’|
正确的方法是什么?我可以将其拆分为2个字符串声明(每个字符串声明将一个字符串文字和一个int并置),但这很丑陋。我也尝试过<<操作符。 谢谢     
已邀请:
        您可能应该为此使用stringstream。
#include <sstream>

std::stringstream s;
s << \"This value shoud be between \" << MIN_VALUE << \" and \" << MAX_VALUE;
message = s.str();
    
        C ++的方法是使用字符串流,然后可以使用<<操作符。它将给您更一致的代码感觉     
        有很多方法可以做到这一点,但我最喜欢的是:
string message(string(\"That value should be between \") + MIN_VALUE + \" and \" + MAX_VALUE);
第一个字面值周围的额外
string()
使得世界上的一切都不同,因为有一个重载的
string::operator+(const char*)
返回了
string
,而
operator+
具有从左到右的关联性,因此整个事情变成了
operator+
调用的链。     
        
#include <sstream>
#include <string>

template <typename T>
std::string Str( const T & t ) {
     std::ostringstream os;
     os << t;
     return os.str();
}



std::string message = \"That value should be between \" + Str( MIN_VALUE ) 
                       + \" and \" + Str( MAX_VALUE );
    
        您可能想要使用这样的字符串流:
std::stringstream msgstream;
msgstream << \"That value should be between \" << MIN_VALUE << \" and \" <<  MAX_VALUE;
std::string message(msgstream.c_str());
    

要回复问题请先登录注册