A
andy
Roland said:Here's a proposal for a simple, efficient, and safe conversion
function:
#include <stdio.h>
#include <string>
inline std::string& itostr (int i, std::string& out) {
std::string::value_type buf[128];
int len = snprintf(buf, sizeof(buf), "%d", i);
if (len > 0 && size_t (len) < sizeof (buf)) {
out.assign(buf, std::string::size_type (len));
} else {
out.clear();
}
return out;
}
Seems good to me. I reckon you could maybe improve on the buffer size
could you as below? Whether the function should assert or throw an
exception on failure is another debate too of course, and whether to
check for the terminator etc :
#include <cstdio>
#include <limits>
#include <string>
#include <stdexcept>
struct itostr_error : public std::exception{
itostr_error(){}
const char* what(){ return "bad itostr";}
};
inline
std::string& itostr (int i, std::string& out)
{
std::string::value_type buf[std::numeric_limits<int>::digits10 +
3];
int len = std::sprintf(buf, "%d", i); //slightly quicker
if (len > 0 && size_t (len) < sizeof (buf)
&& (buf[std::numeric_limits<int>::digits10 + 2]=='\0')) {
out.assign(buf, std::string::size_type (len));
return out;
} else {
throw itostr_error();
}
}
#include <iostream>
int main()
{
try{
std::string str;
itostr(INT_MIN,str);
std::cout << str <<'\n';
}
catch( itostr_error & e){
std::cout << e.what() <<'\n';
}
}
regards
Andy Little