简体   繁体   中英

C++ concatenation between literal and constant

I am new to C++ and I want to know why the line below is not correct. (SERVER_NAME has been defined as a constant)

L"Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << ";"

I get these errors:

error C2296: '<<' : illegal, left operand has type 'const wchar_t [...' 
error C2308: concatenating mismatched strings

Thanks

operator<< is not a concatenation operator, it's a special overloaded operator by stream types to let you send data to stream. It only works if you're using a stream.

You have two options here. First, you can use a std::wstring:

std::wstring(L"Initial Catalog=DatabaseName;Data Source=") + SERVER_NAME + L";";

Or you can use a wstringstream (from the <sstream> header):

std::wstringstream stream;
stream << L"Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << L";"

Use stream.str() to get the resulting string in that case. The stream approach has the advantage that you can use it even if not all the things you want to concatenate are already strings.

If you're printing to an existing stream (like wcout), you can just skip the stringstream and use that directly, of course.

As other answers have pointed out, you can use L"Initial Catalog=DatabaseName;Data Source=" SERVER_NAME L";" if SERVER_NAME is a constant create with #define. If it is a const wchar_t* that won't work however.

<< and >> are not concatenation operators, but rather bitwise shifting operators, something that is totally unrelated.

It's confusing for beginners because they have been overloaded for cout and cin to mean something completely different.

Concatenation of string literals in C and C++ is done without a special operator, so just type:

L"Initial Catalog=DatabaseName;Data Source=" SERVER_NAME L";"

It may be that SERVER_NAME is not a wide-character string. However, what's definately broken is that your ";" is not a wide-character string. Try using L";"

If you want to concatenate this string use std::stringstream

std::stringstream ss;
ss << "Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << ";";
std::string final = ss.str();
std::wstring connectionString = "Initial Catalog=DatabaseName;Data Source=";
connectionString += SERVER_NAME + ";";

Make sure SERVER_NAME is defined as wide-character string, something like this:

const wchar_t *SERVER_NAME = L"testdb";

Or,

std::wstring SERVER_NAME = L"testdb";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM