I found a bug on the function below. When temp = 10. It will convert temp to string '01'. instead of string'10'. I can't tell why? Is there any better t开发者_JAVA百科o convert Num to Str? Thanks.
completed Num2Str() as this,
static bool Num2Str(string& s, const T& value)
{
int temp = static_cast<int>(value); // When temp = 10.
s.push_back(char('0' + temp % 10));
temp /= 10;
while(temp != 0)
{
s.push_back(char('0' + temp % 10));
temp /= 10;
}
if(s.size() == 0)
{
return false;
}
if(s.find_first_not_of("0123456789") != string::npos)
{
return false;
}
return true;
}
Use std::ostringstream
to convert numbers to strings.
Don't use free static functions in C++; use unnamed namespaces instead.
#include<sstream>
#include<string>
namespace {
void f()
{
int value = 42;
std::ostringstream ss;
if( ss << value ) {
std::string s = ss.str();
} else {
// failure
}
}
}
For a solution in the flavour of the existing code (although I'd prefer the existing built int to string conversion):
template<class T>
static std::string Num2Str(const T& value)
{
std::string s;
int temp = static_cast<int>(value);
if (!temp)
{
s = "0";
return s;
}
while(temp != 0)
{
s.insert(0,1,(char('0' + temp % 10)));
temp /= 10;
}
return s;
}
Need to add support for negative values, range checking, etc.
My favorite is the recursive version (mostly in C) for flipping the digits to be in the correct order.
void u2str(string& s, unsigned value){
unsigned d = value % 10;
value /= 10;
if (value > 0 )
u2str(s,value);
s.push_back('0'+d);
}
For 0, you get "0", but in all other cases you don't get leading zeros. As shown it assumes string is more efficient at appending than inserting. However, if inserting is, then you don't need the recursive trick (eg Keith's answer).
You could also use boost::lexical_cast (see http://www.boost.org/doc/libs/1_46_1/libs/conversion/lexical_cast.htm)
For example:
void log_message(const std::string &);
void log_errno(int yoko)
{
log_message("Error " + boost::lexical_cast<std::string>(yoko) + ": " + strerror(yoko));
}
精彩评论