0

I am using SQLITE3 and can successfully read data from a SQLITE database table and display it in C++ like so:

cout << sqlite3_column_text(dbResult, 1);

However, I need to convert the column result into a string. Is there perhaps an easy way in C++ to convert char into string? Have been trying to find a solution, but to no avail.

Any suggestion would be much appreciated.

tadman
  • 208,517
  • 23
  • 234
  • 262
cShellPro
  • 35
  • 1
  • At least (and without knowledge of the sqlite3 API), if you can output it into a stream, you can output into a `std::ostringstream`. Afterwards, you can return the `std::string` with `std::ostringstream::str()`. (Though, if it's really just a `char` then you could assign or add the `char` to a `std::string` directly.) – Scheff's Cat Oct 06 '22 at 05:27
  • Thank you Scheff's Cat Was really hoping there was a more elegant way like in MQL4, where I could just use: "string myResult = CharToStr(sqlite3_column_text(dbResult, 1));" to achieve this. – cShellPro Oct 06 '22 at 05:42
  • Are we really talking about a `char` or a `const char*`? What stops you to write `std::string myResult = sqlite3_column_text(dbResult, 1);`? (Did you even try this?) – Scheff's Cat Oct 06 '22 at 05:46
  • 1
    This is exactly what I am trying, but it throws the following error: ....cpp:3625: error: no viable conversion from 'const unsigned char *' to 'std::string' (aka 'basic_string') – cShellPro Oct 06 '22 at 05:53

1 Answers1

0

According to doc. sqlite3_column_text() is declared as:

const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);

For any reason, it returns a const unsigned char*. (This might be for historical reasons to emphasize the fact that the returned string is UTF-8 encoded.)

Thus, for assignment to a std::string (which can be assigned with const char* expressions among others), a small dirty trick does the job:

std::string myResult = (const char*)sqlite3_column_text(dbResult, 1);

This reclaims the sequence of unsigned chars to be a sequence of chars.

Please, note that the signedness of char is left to the compiler implementation and may be signed or unsigned. (In the major compilers MSVC, g++, clang, it's in fact signed.) Hence, it's accompanied by types signed char and unsigned char to make the signedness explicit (and independent of the used compiler) when necessary. The conversion in the above snippet doesn't change any contents of the returned string — it just makes it compatible for the assignment to std::string.


Googling a bit, I found another Q/A where the answer explains that the "small dirty trick" is legal according to the C++ standard:

Can I turn unsigned char into char and vice versa?

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56