开发者

Adding text to char*

Is it possible to add text to a char*?

Because this code gives errors:

name3 = "SELECT account_id FROM players WHERE name = '" + name + "'";

(na开发者_Go百科me3 = a char*)


Your question is tagged with C++, so use C++. Get rid of your char*'s and use std::string:

std::string name = "...";

std::string name3 = "SELECT account_id FROM players WHERE name = '" + name + "'";

You can "add" two character arrays (char*'s) by allocating a new array large enough to hold both, and copying both strings into the new array. I think you'll agree that std::string is easier, but it also provides less opportunity for you to introduce subtle errors into your code making debugging and maintenance simpler down the road.


You must allocate the memory first, for example:

char* name = new char[ BUFF_SIZE ];

and then use strcpy and strcat, but .. you have tag c++. Use std::string

std::string name3 = "SELECT account_id FROM players WHERE name = '"
                    + 
                    std::string( name ) 
                    + 
                    "'";

or

std::string name3 = "SELECT account_id FROM players WHERE name = '";
name3 += name;
name3 += "'"; // or name3.push_back( ';' );

Note if name is not const char*, but std::string, you don't need from explicit conversions, so refer to meagar's post


You can also use sprintf for what you're describing.

Also, if this is for a database connection you may want to consider using prepared statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜