【问题标题】:Converting an int to std::string将 int 转换为 std::string
【发布时间】:2011-06-07 19:31:24
【问题描述】:

将 int 转换为字符串的最短方法是什么,最好是可内联的?欢迎使用 stl 和 boost 的答案。

【问题讨论】:

标签: c++ string int


【解决方案1】:

嗯,众所周知的方法(在 C++11 之前)是使用流运算符:

#include <sstream>

std::ostringstream s;
int i;

s << i;

std::string converted(s.str());

当然,您可以使用模板函数将其推广到任何类型^^

#include <sstream>

template<typename T>
std::string toString(const T& value)
{
    std::ostringstream oss;
    oss << value;
    return oss.str();
}

【讨论】:

  • 注意:这需要#include &lt;sstream&gt;
  • @TechNyquist:你是​​对的。不意味着可编译,但已更改!
  • 所以你并不是说它是可编译的,但实际上包含它是:)
  • @TechNyquist:是的,还有一些std:: ;)
【解决方案2】:

在包含&lt;sstream&gt;后,您可以使用此函数将int转换为std::string

#include <sstream>

string IntToString (int a)
{
    stringstream temp;
    temp<<a;
    return temp.str();
}

【讨论】:

    【解决方案3】:
    #include <string>
    #include <stdlib.h>
    

    这里是另一种将int转换为字符串的简单方法

    int n = random(65,90);
    std::string str1=(__String::createWithFormat("%c",n)->getCString());
    

    您可以访问此链接了解更多方法 https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/

    【讨论】:

    • 必须包含以下内容才能使用此方法头文件#include #include
    【解决方案4】:

    假设我有integer = 0123456789101112。现在,这个整数可以被stringstream类转换成字符串了。

    这是 C++ 中的代码:

       #include <bits/stdc++.h>
       using namespace std;
       int main()
       {
          int n,i;
          string s;
          stringstream st;
          for(i=0;i<=12;i++)
          {
            st<<i;
          }
          s=st.str();
          cout<<s<<endl;
          return 0;
    
        }
    

    【讨论】:

    • 多年前已经给出了相似但更完整的答案?
    • 是的,但我认为这个答案很完美,因为我没有从以前得到任何有效的答案。
    【解决方案5】:

    如果您不能使用 C++11 中的 std::to_string,您可以按照 cppreference.com 上的定义编写它:

    std::string to_string( int value ) 将有符号十进制整数转换为与 std::sprintf(buf, "%d", value) 为足够大的 buf 生成的内容相同的字符串。

    实施

    #include <cstdio>
    #include <string>
    #include <cassert>
    
    std::string to_string( int x ) {
      int length = snprintf( NULL, 0, "%d", x );
      assert( length >= 0 );
      char* buf = new char[length + 1];
      snprintf( buf, length + 1, "%d", x );
      std::string str( buf );
      delete[] buf;
      return str;
    }
    

    你可以用它做更多的事情。只需使用"%g" 将float 或double 转换为字符串,使用"%x" 将int 转换为十六进制表示,等等。

    【讨论】:

      【解决方案6】:

      你可以在 C++11 中使用std::to_string

      int i = 3;
      std::string str = std::to_string(i);
      

      【讨论】:

      • std::to_string() 在 MinGW 中不起作用,如果有人关心的话。
      • @bparker 对,我猜它已在 gcc 4.8.0 中修复。带有最新 Code::Blocks (13.12) 的 MinGW 仍然具有 gcc 4.7.1。
      【解决方案7】:

      非标准函数,但在最常见的编译器上实现:

      int input = MY_VALUE;
      char buffer[100] = {0};
      int number_base = 10;
      std::string output = itoa(input, buffer, number_base);
      

      更新

      C++11 引入了几个 std::to_string 重载(注意它默认为 base-10)。

      【讨论】:

      • @DevSolar:你应该详细说明。已经给出了 boost 的例子。当未安装 boost 时,大多数编译器都可以使用此解决方案(或者您的要求禁止您出于任何原因使用它)。 ostream 也可以使用,直到您需要将数字字符串保存为二进制、八进制或十六进制格式(例如 base-32)以外的其他格式。
      • 我不喜欢将itoa()stricmp() 等非标准函数作为anything 的答案。
      • 很抱歉冒犯了您的感受,但我确实在第一句话中声明这是一个非标准功能。我没有提到它,但是sprintf 也可以实现 OP 的目标(尽管如果需要除通用基数之外的任何其他内容,仍然会缺乏灵活性)。
      • 是的,您确实说过,而且我没有否决您的回答,即使我很想这样做。所以我认为我们是平的。 ;-)
      【解决方案8】:

      boost::lexical_cast&lt;std::string&gt;(yourint) 来自boost/lexical_cast.hpp

      支持 std::ostream 的所有东西都可以工作,但不如 itoa 等速度快

      它甚至似乎比 stringstream 或 scanf 更快:

      【讨论】:

      • Boost 是你的朋友,如果在标准 C++ 中没有一种简单的方法来做到这一点...我当然喜欢 lexical_cast 带来的东西,但感觉 Boost 对于这种类型来说太过分了任务...
      • 如果他们无法使用 Boost,应该考虑您的受众
      • "欢迎使用 stl 和 boost 的答案。" - 考虑的受众
      【解决方案9】:

      您可以在项目中包含 itoa 的实现。
      这是修改后的 itoa 以与 std::string 一起使用:http://www.strudel.org.uk/itoa/

      【讨论】:

        【解决方案10】:

        以下宏不如一次性使用的ostringstreamboost::lexical_cast 紧凑。

        但是如果你需要在你的代码中反复转换为字符串,这个宏在使用上比每次都直接处理字符串流或显式转换更优雅。

        它还非常通用,因为它可以转换operator&lt;&lt;() 支持的所有内容,甚至可以组合使用。

        定义:

        #include <sstream>
        
        #define SSTR( x ) dynamic_cast< std::ostringstream & >( \
                    ( std::ostringstream() << std::dec << x ) ).str()
        

        说明:

        std::dec 是一种无副作用的方法,可以将匿名 ostringstream 变为通用 ostream,因此 operator&lt;&lt;() 函数查找适用于所有类型。 (如果第一个参数是指针类型,你会遇到麻烦。)

        dynamic_cast 将类型返回到ostringstream,因此您可以在其上调用str()

        用途:

        #include <string>
        
        int main()
        {
            int i = 42;
            std::string s1 = SSTR( i );
        
            int x = 23;
            std::string s2 = SSTR( "i: " << i << ", x: " << x );
            return 0;
        }
        

        【讨论】:

        • @rubenvb:你告诉我如何把它变成一个模板,我会更新我一直在使用这个结构的所有 C++ 项目。
        • @rubenvb:对不起,这不是应该的那么清楚。我看不到如何将其转换为模板(使用 C++98)而不会失去菊花链输出的能力(如我的第二个示例中),或者不得不想出一个复杂的混乱来处理任意数量的参数和参数类型。
        • @DevSolar:inline template&lt;class T&gt; std::string SSTR( T x ) { return dynamic_cast&lt; std::ostringstream &amp; &gt;( (std::ostringstream() &lt;&lt; std::dec &lt;&lt; x) ).str() } 不会吗? (尚未测试,但我确实想知道会出现什么问题以及为什么会出错?
        • @rubenvb:它适用于个人int(我的第一个例子)。但是如果没有main 中的编译器可见的ostream(因为它隐藏在模板函数中),它将尝试在我的第二个示例中查找operator&lt;&lt;() 以查找const char [] - 这会发出嘶哑的声音。我知道 OP 只要求int,但这个更通用的宏非常有用(实际上非​​常普遍),我想我会把它包括在这里。
        • 为了多功能性,我更喜欢模板函数。对于菊花链,也许可以用一点 RTTI 在同一个函数中处理......
        【解决方案11】:
        #include <sstream>
        #include <string>
        const int i = 3;
        std::ostringstream s;
        s << i;
        const std::string i_as_string(s.str());
        

        【讨论】:

        • 这很好,也包括 C++11 之前的技术。这段代码也可以写成:std::ostringstream().operator&lt;&lt;(i).str()
        猜你喜欢
        • 2011-12-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-28
        • 1970-01-01
        相关资源
        最近更新 更多