【问题标题】:Need help on Dissection C++ number 2 sting function需要有关 Dissection C++ 2 号字符串函数的帮助
【发布时间】:2011-03-18 02:32:54
【问题描述】:

我在下面的函数中发现了一个错误。当 temp = 10 时。它将 temp 转换为字符串 '01'。而不是字符串'10'。我说不出为什么? 将 Num 转换为 Str 有更好的方法吗?谢谢。

这样完成了 Num2Str(),

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;
}

【问题讨论】:

标签: c++ function typeconverter


【解决方案1】:

使用std::ostringstream 将数字转换为字符串。

不要在 C++ 中使用免费的静态函数;改用未命名的命名空间。

#include<sstream>
#include<string>

namespace {
void f()
{
    int value = 42;
    std::ostringstream ss;
    if( ss << value ) {
        std::string s = ss.str();
    } else {
      // failure
    }
}
}

【讨论】:

    【解决方案2】:

    对于现有代码风格的解决方案(虽然我更喜欢现有的内置 int 到字符串转换):

    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;
    }
    

    需要添加对负值、范围检查等的支持

    【讨论】:

      【解决方案3】:

      我最喜欢的是递归版本(主要是 C 语言),用于将数字翻转为正确的顺序。

          void u2str(string& s, unsigned value){
              unsigned d = value % 10;
              value /= 10;
              if (value > 0 )
                  u2str(s,value);
              s.push_back('0'+d);
          }
      

      对于 0,您得到“0”,但在所有其他情况下,您不会得到前导零。如图所示,它假设字符串在追加时比插入更有效。但是,如果插入是,那么您不需要递归技巧(例如 Keith 的答案)。

      【讨论】:

        【解决方案4】:

        您也可以使用 boost::lexical_cast(参见 http://www.boost.org/doc/libs/1_46_1/libs/conversion/lexical_cast.htm

        例如:

        void log_message(const std::string &);
        
        void log_errno(int yoko)
        {
            log_message("Error " + boost::lexical_cast<std::string>(yoko) + ": " + strerror(yoko));
        }
        

        【讨论】:

          猜你喜欢
          • 2011-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多