Sprintf() error
There is a Binary2String()
in my project.
It works well for a long time. But it threw exception when vec[0] = 255
on sprintf(temp, "%02d ", vec[i]);
.
Original Code as this,
void Binary2String(const vector<unsigned char>& vec, string& result)
{
if(vec.size() == 0)
return;
for(size_t i = 0; i < vec.size(); i++)
{
char temp[4] = {0};
sprintf(temp, "%02d ", vec[i]);
result.push_back(temp[0]);
result.push_back(temp[1]);
result.push_back(temp[2])开发者_JS百科;
}
}
Then I fixed the bug as this, I can't understand the vector and sprintf() completed.
Does it make sense or not? (I am new to C++. Thank you)
char temp[6] = {0};
sprintf(temp, "%02d ", vec[i]);
result.push_back(temp[0]);
result.push_back(temp[1]);
result.push_back(temp[2]);
result.push_back(temp[3]);
result.push_back(temp[4]);
First of all, %02d
is not the correct format since values can go up to 3 digits (%03d
would be more appropriate). And as Chris states in the comment below, %03hhu
would be the technically correct specifier (to understand %03hhu
, take a look at this cheat sheet).
Second, You need 5 bytes to store the chars "2", "5", "5", " ", 0 (you have an extra space at the end of %02d
). Either drop the space, or extend the buffer to at least 5 chars (as you have done).
Finally, you can convert to string much more reliably this way:
template<typename T> std::string ToString(const T& in) {
std::basic_ostringstream<char> o;
if (!(o << in)) {
// error, throw an exception
}
return o.str();
}
精彩评论