用于将整数转换为字符串 C++ 的 itoa() 替代方案?

发布于 2024-07-07 22:48:47 字数 110 浏览 12 评论 0 原文

我想知道是否有 itoa() 的替代方法来将整数转换为字符串,因为当我在 Visual Studio 中运行它时,我收到警告,当我尝试在 Linux 下构建程序时,我出现编译错误。

I was wondering if there was an alternative to itoa() for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.

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

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

发布评论

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

评论(18

顾挽 2024-07-14 22:48:47

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

#include <string>

std::string s = std::to_string(5);

如果您使用的是 C++11 之前的版本,则可以使用 C++ 流:

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

取自 http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

In C++11 you can use std::to_string:

#include <string>

std::string s = std::to_string(5);

If you're working with prior to C++11, you could use C++ streams:

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

时光暖心i 2024-07-14 22:48:47

boost::lexical_cast 效果很好。

#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
    std::string foo = boost::lexical_cast<std::string>(argc);
}

boost::lexical_cast works pretty well.

#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
    std::string foo = boost::lexical_cast<std::string>(argc);
}
我们的影子 2024-07-14 22:48:47

考古

itoa 是一个非标准辅助函数,旨在补充 atoi 标准函数,并且可能隐藏了 sprintf (其大部分功能可以用 sprintf 实现): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

C 方式

使用 sprintf。 或者 snprintf。 或者你找到的任何工具。

尽管事实上有些函数不在标准中,正如“onebyone”在他的评论中正确提到的那样,大多数编译器都会为您提供替代方案(例如,Visual C++ 有它自己的 _snprintf,如果需要,您可以将其 typedef 为 snprintf)。

C++方式。

使用 C++ 流(在当前情况下为 std::stringstream(甚至是已弃用的 std::strstream,如 Herb Sutter 在他的一本书中提出的,因为它速度更快)。

结论

您使用的是 C++,这意味着你可以选择你想要的方式:

  • 更快的方式(即C方式),但你应该确保代码是应用程序中的瓶颈(过早的优化是邪恶的,等等)并且你的代码是安全的封装以避免缓冲区溢出的风险。

  • 更安全的方法(即 C++ 方法),如果您知道这部分代码并不关键,那么最好确保这部分代码不会因为有人误认为大小或指针而在随机时刻中断(这发生在现实生活中,就像......昨天,在我的电脑上,因为有人认为使用更快的方式而不是真正需要它“很酷”)。

Archeology

itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

The C Way

Use sprintf. Or snprintf. Or whatever tool you find.

Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).

The C++ way.

Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).

Conclusion

You're in C++, which means that you can choose the way you want it:

  • The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.

  • The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it "cool" to use the faster way without really needing it).

完美的未来在梦里 2024-07-14 22:48:47

尝试 sprintf():

char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"

sprintf() 与 printf() 类似,但输出为字符串。

另外,正如 Parappa 在评论中提到的,您可能需要使用 snprintf() 来阻止发生缓冲区溢出(其中您要转换的数字不适合字符串的大小)。它的工作原理如下:

snprintf(str, sizeof(str), "%d", num);

Try sprintf():

char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"

sprintf() is like printf() but outputs to a string.

Also, as Parappa mentioned in the comments, you might want to use snprintf() to stop a buffer overflow from occuring (where the number you're converting doesn't fit the size of your string.) It works like this:

snprintf(str, sizeof(str), "%d", num);
爱她像谁 2024-07-14 22:48:47

在幕后, lexical_cast 会这样做:

std::stringstream str;
str << myint;
std::string result;
str >> result;

如果您不想为此“拖入” boost,那么使用上面的方法是一个很好的解决方案。

Behind the scenes, lexical_cast does this:

std::stringstream str;
str << myint;
std::string result;
str >> result;

If you don't want to "drag in" boost for this, then using the above is a good solution.

七颜 2024-07-14 22:48:47

我们可以在 C++ 中定义自己的 iota 函数:

string itoa(int a)
{
    string ss="";   //create empty string
    while(a)
    {
        int x=a%10;
        a/=10;
        char i='0';
        i=i+x;
        ss=i+ss;      //append new character at the front of the string!
    }
    return ss;
}

不要忘记#include

We can define our own iota function in c++ as:

string itoa(int a)
{
    string ss="";   //create empty string
    while(a)
    {
        int x=a%10;
        a/=10;
        char i='0';
        i=i+x;
        ss=i+ss;      //append new character at the front of the string!
    }
    return ss;
}

Don't forget to #include <string>.

风柔一江水 2024-07-14 22:48:47

С++11 最终解决了这个问题,提供了 std::to_string
此外,boost::lexical_cast对于旧编译器来说是一个方便的工具。

С++11 finally resolves this providing std::to_string.
Also boost::lexical_cast is handy tool for older compilers.

遗心遗梦遗幸福 2024-07-14 22:48:47

我使用这些模板

template <typename T> string toStr(T tmp)
{
    ostringstream out;
    out << tmp;
    return out.str();
}


template <typename T> T strTo(string tmp)
{
    T output;
    istringstream in(tmp);
    in >> output;
    return output;
}

I use these templates

template <typename T> string toStr(T tmp)
{
    ostringstream out;
    out << tmp;
    return out.str();
}


template <typename T> T strTo(string tmp)
{
    T output;
    istringstream in(tmp);
    in >> output;
    return output;
}
绝影如岚 2024-07-14 22:48:47

尝试 Boost.FormatFastFormat,都是高质量的 C++ 库:

int i = 10;
std::string result;

使用 Boost.Format

result = str(boost::format("%1%", i));

或 FastFormat

fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);

显然,它们所做的不仅仅是单个整数的简单转换

Try Boost.Format or FastFormat, both high-quality C++ libraries:

int i = 10;
std::string result;

WIth Boost.Format

result = str(boost::format("%1%", i));

or FastFormat

fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);

Obviously they both do a lot more than a simple conversion of a single integer

酒与心事 2024-07-14 22:48:47

实际上,您可以使用一个巧妙编写的模板函数将任何内容转换为字符串。 此代码示例使用循环在 Win-32 系统中创建子目录。 字符串连接运算符operator+用于连接根与后缀以生成目录名称。 后缀是通过使用模板函数将循环控制变量 i 转换为 C++ 字符串并将其与另一个字符串连接来创建的。

//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>

using namespace std;

string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an   */
/* integer as input and as output,    */
/* returns a C++ string.              */
/* itoa()  returned a C-string (null- */
/* terminated)                        */
/* This function is not needed because*/
/* the following template function    */
/* does it all                        */
/**************************************/   
       string r;
       stringstream s;

       s << x;
       r = s.str();

       return r;

}

template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of   */
/* C++ templates. This function will  */
/* convert anything to a string!      */
/* Precondition:                      */
/* operator<< is defined for type T    */
/**************************************/
       string r;
       stringstream s;

       s << argument;
       r = s.str();

       return r;

}

int main( )
{
    string s;

    cout << "What directory would you like me to make?";

    cin >> s;

    try
    {
      mkdir(s.c_str());
    }
    catch (exception& e) 
    {
      cerr << e.what( ) << endl;
    }

    chdir(s.c_str());

    //Using a loop and string concatenation to make several sub-directories
    for(int i = 0; i < 10; i++)
    {
        s = "Dir_";
        s = s + toString(i);
        mkdir(s.c_str());
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

You can actually convert anything to a string with one cleverly written template function. This code example uses a loop to create subdirectories in a Win-32 system. The string concatenation operator, operator+, is used to concatenate a root with a suffix to generate directory names. The suffix is created by converting the loop control variable, i, to a C++ string, using the template function, and concatenating that with another string.

//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>

using namespace std;

string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an   */
/* integer as input and as output,    */
/* returns a C++ string.              */
/* itoa()  returned a C-string (null- */
/* terminated)                        */
/* This function is not needed because*/
/* the following template function    */
/* does it all                        */
/**************************************/   
       string r;
       stringstream s;

       s << x;
       r = s.str();

       return r;

}

template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of   */
/* C++ templates. This function will  */
/* convert anything to a string!      */
/* Precondition:                      */
/* operator<< is defined for type T    */
/**************************************/
       string r;
       stringstream s;

       s << argument;
       r = s.str();

       return r;

}

int main( )
{
    string s;

    cout << "What directory would you like me to make?";

    cin >> s;

    try
    {
      mkdir(s.c_str());
    }
    catch (exception& e) 
    {
      cerr << e.what( ) << endl;
    }

    chdir(s.c_str());

    //Using a loop and string concatenation to make several sub-directories
    for(int i = 0; i < 10; i++)
    {
        s = "Dir_";
        s = s + toString(i);
        mkdir(s.c_str());
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}
尴尬癌患者 2024-07-14 22:48:47

分配足够长度的字符串,然后使用 snprintf。

Allocate a string of sufficient length, then use snprintf.

死开点丶别碍眼 2024-07-14 22:48:47
int number = 123;

stringstream = s;

s << number;

cout << ss.str() << endl;
int number = 123;

stringstream = s;

s << number;

cout << ss.str() << endl;
晚风撩人 2024-07-14 22:48:47

我不久前编写了这个线程安全函数,对结果非常满意,觉得该算法轻量且精简,性能大约是标准 MSVC _itoa() 函数的 3 倍。

这是链接。 最佳 Base-10 only itoa() 函数? 性能至少是该函数的 10 倍sprintf() 的。 基准测试也是该功能的 QA 测试,如下所示。

start = clock();
for (int i = LONG_MIN; i < LONG_MAX; i++) {
    if (i != atoi(_i32toa(buff, (int32_t)i))) {
        printf("\nError for %i", i);
    }
    if (!i) printf("\nAt zero");
}
printf("\nElapsed time was %f milliseconds", (double)clock() - (double)(start));

关于使用调用者的存储提出了一些愚蠢的建议,这些建议会使结果浮动在调用者地址空间的缓冲区中的某个位置。 别理他们。 正如基准/QA 代码所示,我列出的代码运行良好。

我相信这段代码足够精简,可以在嵌入式环境中使用。 YMMV,当然。

I wrote this thread-safe function some time ago, and am very happy with the results and feel the algorithm is lightweight and lean, with performance that is about 3X the standard MSVC _itoa() function.

Here's the link. Optimal Base-10 only itoa() function? Performance is at least 10X that of sprintf(). The benchmark is also the function's QA test, as follows.

start = clock();
for (int i = LONG_MIN; i < LONG_MAX; i++) {
    if (i != atoi(_i32toa(buff, (int32_t)i))) {
        printf("\nError for %i", i);
    }
    if (!i) printf("\nAt zero");
}
printf("\nElapsed time was %f milliseconds", (double)clock() - (double)(start));

There are some silly suggestions made about using the caller's storage that would leave the result floating somewhere in a buffer in the caller's address space. Ignore them. The code I listed works perfectly, as the benchmark/QA code demonstrates.

I believe this code is lean enough to use in an embedded environment. YMMV, of course.

﹉夏雨初晴づ 2024-07-14 22:48:47

IMO,最好的答案是这里提供的功能:

http:// www.jb.man.ac.uk/~slowe/cpp/itoa.html

它模仿许多库提供的非 ANSI 函数。

char* itoa(int value, char* result, int base);

它的速度也快如闪电,并且在 -O3 下优化得很好,而您不使用 c++ string_format() ...或 sprintf 的原因是它们太慢了,对吧?

The best answer, IMO, is the function provided here:

http://www.jb.man.ac.uk/~slowe/cpp/itoa.html

It mimics the non-ANSI function provided by many libs.

char* itoa(int value, char* result, int base);

It's also lightning fast and optimizes well under -O3, and the reason you're not using c++ string_format() ... or sprintf is that they are too slow, right?

自演自醉 2024-07-14 22:48:47

如果您对快速且安全的整数到字符串转换方法感兴趣并且不限于标准库,我可以推荐 format_int 方法/fmtlib/fmt" rel="nofollow noreferrer">{fmt} 库:

fmt::format_int(42).str();   // convert to std::string
fmt::format_int(42).c_str(); // convert and get as a C string
                             // (mind the lifetime, same as std::string::c_str())

根据 来自 Boost Karma 的整数到字符串转换基准,此方法比 glibc 的 sprintfstd::stringstream 快几倍。 它甚至比 Boost Karma 自己的 int_generator 还要快,独立基准

免责声明:我是这个库的作者。

If you are interested in fast as well as safe integer to string conversion method and not limited to the standard library, I can recommend the format_int method from the {fmt} library:

fmt::format_int(42).str();   // convert to std::string
fmt::format_int(42).c_str(); // convert and get as a C string
                             // (mind the lifetime, same as std::string::c_str())

According to the integer to string conversion benchmarks from Boost Karma, this method several times faster than glibc's sprintf or std::stringstream. It is even faster than Boost Karma's own int_generator as was confirm by an independent benchmark.

Disclaimer: I'm the author of this library.

捎一片雪花 2024-07-14 22:48:47

请注意,所有 stringstream 方法可能涉及锁定使用区域设置对象进行格式化。 如果您从多个线程使用此转换,则可能需要警惕...

请参阅此处了解更多信息。 在 C++ 中将数字转换为指定长度的字符串< /a>

Note that all of the stringstream methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...

See here for more. Convert a number to a string with specified length in C++

余生再见 2024-07-14 22:48:47

在 Windows CE 派生平台上,默认情况下没有 iostream。 最好使用 _itoa<> 系列,通常是 _itow<> (因为大多数字符串内容都是 Unicode)。

On Windows CE derived platforms, there are no iostreams by default. The way to go there is preferaby with the _itoa<> family, usually _itow<> (since most string stuff are Unicode there anyway).

安静被遗忘 2024-07-14 22:48:47

从技术上讲,上述大多数建议都不是 C++,而是 C 解决方案。

查看 std::stringstream 的使用。

Most of the above suggestions technically aren't C++, they're C solutions.

Look into the use of std::stringstream.

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