我是C ++的新手,我想知道为什么下面的行不正确。 (SERVER_NAME已被定义为常量)
L"Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << ";"
我收到这些错误:
error C2296: '<<' : illegal, left operand has type 'const wchar_t [...'
error C2308: concatenating mismatched strings
由于
答案 0 :(得分:6)
运营商LT;&LT;不是连接运算符,它是流类型的特殊重载运算符,允许您将数据发送到流。它仅在您使用流时才有效。
这里有两种选择。首先,您可以使用std :: wstring:
std::wstring(L"Initial Catalog=DatabaseName;Data Source=") + SERVER_NAME + L";";
或者你可以使用wstringstream(来自<sstream>
标题):
std::wstringstream stream;
stream << L"Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << L";"
在这种情况下,使用stream.str()
获取生成的字符串。流方法的优点是即使并非所有要连接的东西都已经是字符串,也可以使用它。
如果你要打印到现有的流(如wcout),你可以跳过字符串流并直接使用它。
正如其他答案所指出的,如果SERVER_NAME是使用#define创建的常量,则可以使用L"Initial Catalog=DatabaseName;Data Source=" SERVER_NAME L";"
。如果它是const wchar_t*
则不起作用。
答案 1 :(得分:2)
<<
和>>
不是连接运算符,而是逐位转换运算符,这是完全不相关的。
这对于初学者来说很困惑,因为cout
和cin
已经超载,意味着完全不同的东西。
C和C ++中字符串文字的连接是在没有特殊操作符的情况下完成的,所以只需键入:
L"Initial Catalog=DatabaseName;Data Source=" SERVER_NAME L";"
答案 2 :(得分:1)
SERVER_NAME
可能不是宽字符串。但是,肯定会破坏的是";"
不是宽字符串。尝试使用L";"
答案 3 :(得分:1)
如果要连接此字符串,请使用std :: stringstream
std::stringstream ss;
ss << "Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << ";";
std::string final = ss.str();
答案 4 :(得分:0)
std::wstring connectionString = "Initial Catalog=DatabaseName;Data Source=";
connectionString += SERVER_NAME + ";";
确保将SERVER_NAME
定义为宽字符串,如下所示:
const wchar_t *SERVER_NAME = L"testdb";
或者,
std::wstring SERVER_NAME = L"testdb";