简体   繁体   English

将 int 转换为 std::string

[英]Converting an int to std::string

What is the shortest way, preferably inline-able, to convert an int to a string?将 int 转换为字符串的最短方法是什么,最好是内联的? Answers using stl and boost will be welcomed.欢迎使用 stl 和 boost 的答案。

You can use std::to_string in C++11您可以在 C++11 中使用std::to_string

int i = 3;
std::string str = std::to_string(i);
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());

boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp boost::lexical_cast<std::string>(yourint)来自boost/lexical_cast.hpp

Work's for everything with std::ostream support, but is not as fast as, for example, itoa适用于支持 std::ostream 的所有内容,但速度不如itoa

It even appears to be faster than stringstream or scanf:它甚至似乎比 stringstream 或 scanf 更快:

Well, the well known way (before C++11) to do that is using the stream operator :嗯,众所周知的方法(在 C++11 之前)是使用流运算符:

#include <sstream>

std::ostringstream s;
int i;

s << i;

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

Of course, you can generalize it for any type using a template function ^^当然,您可以使用模板函数将其概括为任何类型 ^^

#include <sstream>

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

If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:如果您不能使用 C++11 中的std::to_string ,您可以按照 cppreference.com 上的定义编写它:

std::string to_string( int value ) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf. std::string to_string( int value )将一个有符号十进制整数转换为一个字符串,其内容与std::sprintf(buf, "%d", value)为足够大的 buf 产生的内容相同。

Implementation实施

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

You can do more with it.你可以用它做更多的事情。 Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.只需使用"%g"将float或double转换为字符串,使用"%x"将int转换为十六进制表示,等等。

Non-standard function, but its implemented on most common compilers:非标准函数,但它在最常见的编译器上实现:

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

Update更新

C++11 introduced several std::to_string overloads (note that it defaults to base-10). C++11 引入了几个std::to_string重载(注意它默认为 base-10)。

The following macro is not quite as compact as a single-use ostringstream or boost::lexical_cast .下面的宏不像一次性使用的ostringstreamboost::lexical_cast那样紧凑。

But if you need conversion-to-string repeatedly in your code, this macro is more elegant in use than directly handling stringstreams or explicit casting every time.但是如果你需要在你的代码中重复转换为字符串,这个宏在使用中比每次直接处理字符串流或显式转换更优雅。

It is also very versatile, as it converts everything supported by operator<<() , even in combination.它也非常通用,因为它可以转换operator<<()支持的所有内容,甚至可以组合使用。

Definition:定义:

#include <sstream>

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

Explanation:说明:

The std::dec is a side-effect-free way to make the anonymous ostringstream into a generic ostream so operator<<() function lookup works correctly for all types. std::dec是一种无副作用的方法,可以将匿名ostringstream转换为通用ostream因此operator<<()函数查找对所有类型都能正常工作。 (You get into trouble otherwise if the first argument is a pointer type.) (否则,如果第一个参数是指针类型,则会遇到麻烦。)

The dynamic_cast returns the type back to ostringstream so you can call str() on it. dynamic_cast将类型返回给ostringstream因此您可以对其调用str()

Use:使用:

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

You can use this function to convert int to std::string after including <sstream> :在包含<sstream>之后,您可以使用此函数将int转换为std::string

#include <sstream>

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

You might include the implementation of itoa in your project.您可能会在您的项目中包含 itoa 的实现。
Here's itoa modified to work with std::string: http://www.strudel.org.uk/itoa/这是 itoa 修改为与 std::string 一起使用: http : //www.strudel.org.uk/itoa/

#include <string>
#include <stdlib.h>

Here, is another easy way to convert int to string这是将 int 转换为 string 的另一种简单方法

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

you may visit this link for more methods https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/您可以访问此链接以获取更多方法https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/

Suppose I have integer = 0123456789101112 .假设我有integer = 0123456789101112 Now, this integer can be converted into a string by the stringstream class.现在,这个整数可以被stringstream类转换成字符串。

Here is the code in C++:这是 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;

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM