将 int 转换为 std::string

发布于 2024-10-12 02:14:00 字数 61 浏览 6 评论 0原文

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

What is the shortest way, preferably inline-able, to convert an int to a string? Answers using stl and boost will be welcomed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

夜声 2024-10-19 02:14:01

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

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 重载(请注意,它默认为以 10 为基数)。

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).

哭泣的笑容 2024-10-19 02:14:01

以下宏并不像一次性使用的 ostringstream 或 boost::lexical_cast 那样紧凑。

但是,如果您需要在代码中重复转换为字符串,则使用此宏比每次直接处理字符串流或显式转换更优雅。

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

定义:

#include <sstream>

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

解释:

std::dec 是一种无副作用的方法,可将匿名 ostringstream 转换为通用 ostream 因此,operator<<() 函数查找对于所有类型都可以正常工作。 (如果第一个参数是指针类型,否则您会遇到麻烦。)

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

The following macro is not quite as compact as a single-use ostringstream or boost::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.

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. (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.

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;
}
┼── 2024-10-19 02:14:01

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

#include <sstream>

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

You can use this function to convert int to std::string after including <sstream>:

#include <sstream>

string IntToString (int a)
{
    stringstream temp;
    temp<<a;
    return temp.str();
}
抚笙 2024-10-19 02:14:01

虽然 std::to_string 是一个应该记住的简单工具,但从 C++20 开始,您可以包含 ,它允许更详细的对话intstring

#include <iostream>
#include <locale>
#include <format>

int main()
{
    using std::cout, std::endl;

    auto const n = 42;
    cout << std::format("{}", n) << endl;
    cout << std::format("{:d}", n) << endl;
    cout << std::format("{:#x}", n) << endl;
    cout << std::format("{:#o}", n) << endl;
    cout << std::format("{:#b}", n) << endl;
}

输出:

42
42
0x2a
052
0b101010

While std::to_string is a straightforward tool that should be kept in mind, starting with C++20, you may include <format>, which allows for more elaborates conversations from int to string:

#include <iostream>
#include <locale>
#include <format>

int main()
{
    using std::cout, std::endl;

    auto const n = 42;
    cout << std::format("{}", n) << endl;
    cout << std::format("{:d}", n) << endl;
    cout << std::format("{:#x}", n) << endl;
    cout << std::format("{:#o}", n) << endl;
    cout << std::format("{:#b}", n) << endl;
}

output:

42
42
0x2a
052
0b101010
强者自强 2024-10-19 02:14:01

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

You might include the implementation of itoa in your project.
Here's itoa modified to work with std::string: http://www.strudel.org.uk/itoa/

再可℃爱ぅ一点好了 2024-10-19 02:14:01

假设我有 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;

    }

Suppose I have integer = 0123456789101112. Now, this integer can be converted into a string by the stringstream class.

Here is the code in 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;

    }
迷荒 2024-10-19 02:14:01
#include <string>
#include <stdlib.h>

这是另一种将 int 转换为 string 的简单方法,

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 <string>
#include <stdlib.h>

Here, is another easy way to convert int to 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/

掌心的温暖 2024-10-19 02:14:00

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

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

You can use std::to_string in C++11

int i = 3;
std::string str = std::to_string(i);
枕花眠 2024-10-19 02:14:00
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());
吹梦到西洲 2024-10-19 02:14:00

那么,众所周知的方法(在 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();
}

Well, the well known way (before C++11) to do that is using the stream operator :

#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();
}
咆哮 2024-10-19 02:14:00

来自 boost/lexical_cast.hppboost::lexical_cast(yourint)

可以在 std::ostream 支持的情况下工作,但速度不如,例如, itoa

甚至看起来比 stringstream 或 scanf 更快:

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

Work's for everything with std::ostream support, but is not as fast as, for example, itoa

It even appears to be faster than stringstream or scanf:

一曲琵琶半遮面シ 2024-10-19 02:14:00

如果您无法使用 std::to_string从 C++11 开始,您可以按照 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 转换为十六进制表示形式,依此类推。

If you cannot use std::to_string from C++11, you can write it as it is defined on 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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文