c++ const mysqlpp::String ambiguous error

c++ const mysqlpp::String ambiguous error

本文关键字:ambiguous error String c++ mysqlpp const      更新时间:2023-10-16

我是 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 与其他接受字符*的普通函数一起使用呢?

我在这里寻找一些提示,但被卡住了。

我已经尝试过转换之类的事情..

ares[i]["description"].c_str();

这给出了从"常量字符*"到"字符*"的无效转换

char * c = ares[i]["description"].c_str()

这给出了类似的错误。

所以我在这一点上有点迷茫,如何在其他地方使用 mysqlpp::String,将其与采用 char* 或 std::string 的函数一起使用的最佳方法是什么?

模棱两可的位是什么?

strtok将更改您传入的字符串,在每个标记后插入字符串终止字符0x0。所以你需要一个char*,但c_str返回一个const char*

如果要使用strtok,则需要获取c_str()返回的const char*的副本。可能最简单的方法是使用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);
相关文章: