简体   繁体   English

将const * char []变量与char []连接

[英]Concatenate a const *char[] variable with a char[]

I'm making a connection between C++ and MySql, and I was trying to do something like this: 我正在C ++和MySql之间建立连接,而我试图做这样的事情:

int id=1;
const char *sql = "delete from register where id=";
strcat(*sql, itoa(id));

But I can't because itoa(id) does not generate a *char[] variable. 但是我不能,因为itoa(id)不会生成*char[]变量。

What can I do? 我能做什么?

Double-check the docs for itoa . 仔细检查docs是否为itoa It takes three arguments and will write the value of your number to the string you provide. 它带有三个参数,并将您的数字值写入您提供的字符串。 http://www.cplusplus.com/reference/cstdlib/itoa/ http://www.cplusplus.com/reference/cstdlib/itoa/

It would be easier to do the following though. 不过,执行以下操作会更容易。

char string[MAX_LENGTH];
snprintf(string, MAX_LENGTH-1, "delete from register where id = %d", id);

You can't concatenate onto a string literal. 您不能连接到字符串文字上。 You have to copy the string literal to a separate buffer, and then concatenate onto that. 您必须将字符串文字复制到单独的缓冲区中,然后串联到该缓冲区上。 Also, itoa() requires a buffer of its own, too: 另外, itoa()需要自己的缓冲区:

int id = 1;
char sql_buffer[50];
char id_buffer[16];
strcpy(sql_buffer, "delete from register where id=");
strcat(sql_buffer, itoa(id, id_buffer, 10));

Or: 要么:

int id = 1;
char sql_buffer[50] = "delete from register where id=";
char id_buffer[16];
strcat(sql_buffer, itoa(id, id_buffer, 10));

Alternatively, use snprintf() instead: 或者,使用snprintf()代替:

int id = 1;
char sql_buffer[50];
snprintf(sql_buffer, sizeof(sql_buffer), "delete from register where id=%d", id);

But, either way, these are C ways to do things. 但是,无论哪种方式,这些都是C的做事方式。 The C++ way is to use a std::ostringstream instead: C ++的方法是使用std::ostringstream代替:

#include <string>
#include <sstream>

int id = 1;
std::ostringstream oss;
oss << "delete from register where id=" << id;
std::string sql = oss.str();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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