sqlite3_column_text返回一个const unsigned char*,如何将其转换为std :: string?我试过std :: string(),但是我收到了一个错误.
码:
temp_doc.uuid = std::string(sqlite3_column_text(this->stmts.read_documents, 0));
Run Code Online (Sandbox Code Playgroud)
错误:
1>.\storage_manager.cpp(109) : error C2440: '<function-style-cast>' : cannot convert from 'const unsigned char *' to 'std::string'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
Run Code Online (Sandbox Code Playgroud)
Reu*_*nen 50
你可以尝试:
temp_doc.uuid = std::string(reinterpret_cast<const char*>(
sqlite3_column_text(this->stmts.read_documents, 0)
));
Run Code Online (Sandbox Code Playgroud)
虽然std::string可以有一个构造函数const unsigned char*,显然它没有.
那为什么不呢?你可以看看这个有点相关的问题:为什么C++流使用char而不是unsigned char?
小智 20
在实际上,您实际上需要一串无符号字符,您可以创建自己的类型:
typedef std::basic_string <unsigned char> ustring;
Run Code Online (Sandbox Code Playgroud)
那么你应该可以这样说:
ustring s = sqlite3_column_text(this->stmts.read_documents, 0);
Run Code Online (Sandbox Code Playgroud)
Mik*_*ler 16
人们通常使用(unsigned char*)类型的原因是为了表明数据是二进制而不是纯ASCII文本.我知道libxml会这样做,从它的外观来看,sqlite正在做同样的事情.
您从sqlite调用中获取的数据可能是UTF-8编码的Unicode文本.虽然reinterpret_cast似乎可以正常工作,但如果有人在非纯ASCII字段中存储文本,那么您的程序可能不会表现良好.
std :: string类在设计时没有考虑到Unicode,所以如果你要求字符串的length(),你将得到字节数,在UTF-8中,它不一定是同一个东西作为字符数.
简短的回答:如果您确定数据只是ASCII,那么简单的强制转换可能会起作用.如果它可以是任何UTF-8数据,那么您需要以更智能的方式处理编码/解码.