Monday, 19 August 2013

C++ std::stringstream not implicitely converting unsigned char

C++ std::stringstream not implicitely converting unsigned char

I'm using a stringstream in C++ to build (many) SQL queries before
executing them.
mQuery << "INSERT INTO table (col1, col2, col3) VALUES(" << val1 << ", "
<< val2 << ", 0)";
I was kind of happy because it saved me a lot of redundant code, but then
I started getting weird SQL errors:
1064: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'X, 0)'
/code/pre
pWhere the X stands for some weird garbage character./p
pI use the stringstream to read all kinds of numeric types into the query
string. It seems that whenever I read an uint8_t (which is a typedef for
unsigned char on my box), it will not convert it to the string
representation of its number, but rather interpret it as a character in
what I suppose is ASCII./p
pMy first question is, why does it have that behaviour?
More importantly, I'm interested to know if there is a way to change this
behaviour?/p
pCasting to a higher byte numeric doesn't seem like the most efficient way
to handle it, but it works. However, there are so many queries that I
would have to add a lot of casts into the code. It would also not be
coherent with the rest of the variables./p

No comments:

Post a Comment