【问题标题】:How can I convert an int to a string in C++11 without using to_string or stoi?如何在不使用 to_string 或 stoi 的情况下将 int 转换为 C++11 中的字符串?
【发布时间】:2015-09-07 13:16:17
【问题描述】:

我知道这听起来很愚蠢,但我在 Windows7 上使用 MinGW32,并且“to_string 未在此范围内声明。” It's an actual GCC Bug,我关注了these instructions,但他们没有工作。那么,如何在不使用 to_stringstoi 的情况下将 int 转换为 C++11 中的字符串? (另外,我启用了-std=c++11 标志)。

【问题讨论】:

  • 嗯,你可以使用支持它的 MinGW-w64 代替
  • 您可以使用sprintf。实际上有很多选项 - atoi 和公司(不是很标准)、字符串流、printf 函数。
  • @MattMcNabb 问题是关于将整数格式化为字符串,而不是将字符串解析为整数
  • to_stringstoi 是相反的。你想做什么?
  • @PanagiotisKanavos 那你为什么提到atoi

标签: c++ string c++11 gcc


【解决方案1】:

这不是最快的方法,但你可以这样做:

#include <string>
#include <sstream>
#include <iostream>

template<typename ValueType>
std::string stringulate(ValueType v)
{
    std::ostringstream oss;
    oss << v;
    return oss.str();
}

int main()
{
    std::cout << ("string value: " + stringulate(5.98)) << '\n';
}

【讨论】:

    【解决方案2】:

    我想换个方式回答:只要得到 mingw-w64。

    说真的,MinGW32 问题太多了,甚至都不好笑:

    使用 MinGW-w64,您可以免费获得:

    • 支持 Windows Unicode 入口点 (wmain/wWinMain)
    • 更好的 C99 支持
    • 更好的 C++11 支持(正如您在问题中看到的那样!)
    • 大文件支持
    • 支持 C++11 线程
    • 支持 Windows 64 位
    • 交叉编译!这样您就可以在自己喜欢的平台上使用 Windows 应用了。

    【讨论】:

    • 从 MinGW-w64 4.9.2 开始,还支持 C++14(也支持 C11 IIRC)。
    • 好吧,你已经说服了我哈哈。。我会卸载它并下载mingw-w64。
    【解决方案3】:

    您可以使用stringstream

    #include <string>
    #include <sstream>
    #include <iostream>
    using namespace std;
    
    int main() {
        int num = 12345;
        stringstream ss;
        ss << num;
        string str;
        ss >> str;
        cout << str << endl;
        return 0;
    }
    

    【讨论】:

      【解决方案4】:

      你可以滚动你自己的函数来做到这一点。

      std::string convert_int_to_string (int x) {
        if ( x < 0 )
          return std::string("-") + convert_int_to_string(-x);
        if ( x < 10 )
          return std::string(1, x + '0');
        return convert_int_to_string(x/10) + convert_int_to_string(x%10);
      }
      

      【讨论】:

      • “你可以”!=“你应该”。只是指出另一件可能的事情。
      【解决方案5】:

      尽管以前的答案更好,但我想为您提供另一种可能性,以按照下一个旧学校代码实现 INT 到 STRING 方法:

      #include <string>
      
      std::string int2string(int value) {
          char buffer[20]; // Max num of digits for 64 bit number
          sprintf(buffer,"%d", value);
          return std::string(buffer);
      }
      

      【讨论】:

      • 会导致 64 位整数系统上的缓冲区溢出
      • 不行,因为 64bit 需要 19 位(在示例中有 20 位缓冲区)9,223,372,036,854,775,807(19 位)
      • 你忘了减号
      • 不,因为缓冲区有 20 个字节代表 19 位数字(符号额外 1 个字节)
      • 你忘了空终止符
      猜你喜欢
      • 2013-10-19
      • 2013-07-08
      • 2018-05-31
      • 2022-07-05
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多