Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const unsigned char * to std::string

Tags:

c++

std

sqlite3_column_text returns a const unsigned char*, how do I convert this to a std::string? I've tried std::string(), but I get an error.

Code:

temp_doc.uuid = std::string(sqlite3_column_text(this->stmts.read_documents, 0)); 

Error:

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 
like image 900
LM. Avatar asked Apr 29 '09 20:04

LM.


People also ask

Can you assign a const char * to a string?

You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .

What is const unsigned char *?

const char* is useful for pointer to a string that will not change. ie your program will print some string, like the same welcome messages every time it starts. The unsigned version is useful for pointer to a binary sequence you may want to write too a file.

Should I use std::string or * char?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.

How do I get const char from std::string?

You can use the c_str() method of the string class to get a const char* with the string contents.


1 Answers

You could try:

temp_doc.uuid = std::string(reinterpret_cast<const char*>(       sqlite3_column_text(this->stmts.read_documents, 0)   )); 

While std::string could have a constructor that takes const unsigned char*, apparently it does not.

Why not, then? You could have a look at this somewhat related question: Why do C++ streams use char instead of unsigned char?

like image 59
Reunanen Avatar answered Oct 01 '22 13:10

Reunanen