我是C ++的新手,刚用C ++用mysql ++。h查询sql数据库
SQL查询本身有效,我可以打印出结果。
char *token;
Query query = conn.query();
query << "SELECT title, description FROM mydb.mytable LIMIT 2";
StoreQueryResult ares = query.store();
for (size_t i = 0; i < ares.num_rows(); i++) {
cout << "Title: " << ares[i]["title"] << " - Description: " << ares[i]["description"] << endl;
const char delim[] = "; \t";
//Error when I add this line
//token = strtok( ares[i]["description"] , delim);
//rest of strtok code which works with normal strings, but not mysqlstring
...
}
关键问题是我试图用行将描述解析为单词
token = strtok( ares[i]["description"] , delim);
我得到错误
error: conversion from ‘const mysqlpp::String’ to ‘char*’ is ambiguous
所以我的理解是strtok需要一个char *并且conn返回一个const mysqlpp :: String,我猜这很有意义。但是然后我如何将mysqlpp :: String与其他采用char *的普通函数一起使用?
我一直在这里寻找一些提示,但被卡住了。
我已经尝试过类似的转换。
ares[i]["description"].c_str();
从“ const char *”到“ char *”的无效转换
char * c = ares[i]["description"].c_str()
这给出了类似的错误。
所以我有点迷失了,如何在其他地方使用mysqlpp :: String,用带char *或std :: string的函数使用它的最佳方法是什么?
含糊不清的地方是什么?
strtok
会更改您传递的字符串,因为它会0x0
在每个令牌后插入字符串终止符。因此,您需要一个char*
,但c_str
返回const char*
。
如果要使用strtok
,则需要获取const char*
返回的副本c_str()
。可能最简单的方法是使用strdup
:
char* c = strdup(ares[i]["description"].c_str());
token = strtok(c, delim);
...
free(c);
要么:
std::string s = ares[i]["description"].c_str();
char* c = s.data(); // or &s[0] prior to C++17...
token = strtok(c, delim);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句