我正在尝试将整数数据转换为字符串,但我收到错误cannot convert 'int*' to 'const char*' for argument '2' to 'char* strcat(char*, const char*)'
#include <iostream>
using namespace std;
#include "sqlite3.h"
#include<string.h>
#include <sstream>
#define STRING_MAX 32
typedef struct metadata_t
{
char session_username[256];
int user_id[256];
int session_id[256];
char buffer[256];
}metadata_t;
void insertdata1(metadata_t *data);
int main (int argc, const char * argv[])
{
struct metadata_t *data;
cin >> *data->user_id;
cin >> data->session_username;
cin >> *data->session_id;
cin >> data->buffer;
insertdata1(data);
}
void insertdata1(metadata_t *data)
{
// char *buff1,*buff2;
sqlite3 *db;
sqlite3_open("test1.db", & db);
string createQuery = "CREATE TABLE IF NOT EXISTS items (user_id INTEGER PRIMARY KEY, session_username TEXT,Session_id INTEGER,buffer TEXT,));";
sqlite3_stmt *createStmt;
cout << "Creating Table Statement" << endl;
sqlite3_prepare(db, createQuery.c_str(), createQuery.size(), &createStmt, NULL);
cout << "Stepping Table Statement" << endl;
if (sqlite3_step(createStmt) != SQLITE_DONE) cout << "Didn't Create Table!" << endl;
//itoa(*data->userid,buff1,10); // not work
//itoa(*data->userphone,buff2,10);// Integer to String Conversion
/* std::string ss;
ss << *data->user_id;
ss << *data->session_id;
std::string user_Id = ss.str();
std::string session_Id = ss.str(); */ // not working
char *a="(";
char *d=")";
char *b="'";
char *c=",";
char str1[1000];
char * str2 = "";
char * g = ";";
strcpy(str1, "INSERT INTO items (user_id,session_username,session_id,buffer)VALUES");
strcat(str1,a);
strcat(str1,b);
strcat(str1,data->user_id);
strcat(str1,b);
strcat(str1,c);
strcat(str1,b);
strcat(str1,data->session_username);
strcat(str1,b);
strcat(str1,c);
strcat(str1,b);
strcat(str1,data->session_id);
strcat(str1,b);
strcat(str1,c);
strcat(str1,b);
strcat(str1,data->buffer);
strcat(str1,b);
strcat(str1,d);
strcat(str1,g);
std::string insertQuery = str1; // WORKS!
sqlite3_stmt *insertStmt;
cout << "Creating Insert Statement" << endl;
sqlite3_prepare(db, insertQuery.c_str(), insertQuery.size(), &insertStmt, NULL);
cout << "Stepping Insert Statement" << endl;
if (sqlite3_step(insertStmt) != SQLITE_DONE) cout << "Didn't Insert Item!" << endl;
}**
答案 0 :(得分:2)
建议使用std::ostringstream
(您需要#include <sstream>
)来构建查询:
std::ostringstream str1;
str1 << "INSERT INTO items (user_id,session_username,session_id,buffer)VALUES"
<< a
<< b // and so on
<< g;
const std::string insertQuery = str1.str();
以下内容不分配任何内存,只是声明一个指针(C ++中不需要struct
):
struct metadata_t *data;
任何取消引用它的尝试都会导致未定义的行为,很可能是一个分段错误:
cin >> *data->user_id;
只是在堆栈上声明它:
metadata_t data;
并将其地址(或通过引用传递)传递给insertdata1()
:
insertdata1(&data);
首选std::string
至char*
或char[]
:
struct metadata_t
{
std::string session_username;
int user_id[256]; // Did you really mean an array of int here ?
int session_id[256];
std::string buffer;
};