3

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

2 Answers 2

4

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*.

Sign up to request clarification or add additional context in comments.

Comments

3

The problem is not with sqlite3_column_text.

printf format specifier %s expects a C string (char pointer).

As printf can't inspect what values are passed on the stack, so it has to trust the format specifier. Because the format specifier is %s, it reads an argument as it was a char pointer (it's not), but by coincidence, it's printing the wrong result, rather than crashing.

std::string exposes a function that gets you a read-only corresponding C string, so, for example, your the second case will be:

// Get a C string from std::string
printf("Result2: %s", try1.c_str());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.