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

时间:2018-11-26 01:32:47

标签: c++ mysql

我正在C ++和MySql之间建立连接,而我正试图做这样的事情:

longSeries = []
currentSeries=[]
for i in range (len(lst)-1):
    if i == 0:
        currentSeries = [lst[0]]
    if(abs(lst[i] - lst[i+1]) % 2 ==  1):
        currentSeries.append(lst[i+1])
    else:
        currentSeries = [lst[i+1]]
    if(len(currentSeries) > len(longSeries)):
        longSeries = currentSeries


print ("The longest series is: " +str(longSeries))
print(len(longSeries))

但是我不能,因为int id=1; const char *sql = "delete from register where id="; strcat(*sql, itoa(id)); 不会生成itoa(id)变量。

我该怎么办?

2 个答案:

答案 0 :(得分:2)

仔细检查itoa的文档。它带有三个参数,并将您的数字值写入您提供的字符串。 http://www.cplusplus.com/reference/cstdlib/itoa/

尽管这样做比较容易。

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

答案 1 :(得分:0)

您不能连接到字符串文字上。您必须将字符串文字复制到单独的缓冲区中,然后串联到该缓冲区上。另外,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));

或者:

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

或者,使用snprintf()代替:

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

但是,无论哪种方式,这些都是C的做事方式。 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();