Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting sqlite result to std::string in C++

Im querying a sqlite db, but i need to convert the result (a TEXT attribute) to a C++ std::string. I feel like this should not be hard to accomplish, but im having trouble.

sqlite3_open("sqlite.db", &db);
std::string str = "SELECT something FROM table";
sqlite3_prepare_v2(db,
str.c_str(),
-1,
&m_statement,
0);

sqlite3_step(m_statement);
// OBS: 3rd party printf, cannot use std::cout in this environment
printf("Result1: %s",sqlite3_column_text(m_statement,0)); // OK! Result is printed

string try1 = string(
    reinterpret_cast<const char*>(sqlite3_column_text(m_statement,0))); 
printf("Result2: %s",try1); // null

stringstream ss;
ss << sqlite3_column_text(m_statement,0);
printf("Result3: %s",ss.str()); // null
like image 417
user1202032 Avatar asked Dec 06 '25 04:12

user1202032


1 Answers

Your problem isn't related to sqlite. When you use %s with printf, printf expects a char * NOT a std::string.

For example change this:

 printf("Result2: %s",try1); // null

to

 printf("Result2: %s",try1.c_str()); 

and see what happens.

C++ has two primary ways of implementing strings. The legacy C string (char*) and the std::string class found in the C++ standard library. If you deal with C APIs, you'll be dealing mostly with the former. printf and sqlite* are both from C APIs, so expect to deal with char*.

like image 138
Doug T. Avatar answered Dec 07 '25 18:12

Doug T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!