Easiest way to convert int to string in C++

2018-12-31 02:10发布

What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?

(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

25条回答
冷夜・残月
2楼-- · 2018-12-31 02:12
string number_to_string(int x){
    if(!x) return "0";
        string s,s2;
        while(x){
            s.push_back(x%10 + '0');
            x/=10;
        }
    reverse(s.begin(),s.end());
    return s;
}
查看更多
ら面具成の殇う
3楼-- · 2018-12-31 02:14
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs,"%d",timeStart.elapsed()/1000);
sprintf(bufMs,"%d",timeStart.elapsed()%1000);
查看更多
查无此人
4楼-- · 2018-12-31 02:15

If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is a convenient example:

int n = 27;
char s[8];

If you are converting a two-digit number:

*(int32_t*)s = 0x3030 | (n/10) | (n%10) << 8;

If you are converting a three-digit number:

*(int32_t*)s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;

If you are converting a four-digit number:

*(int64_t*)s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;

And so on up to seven-digit numbers :)

查看更多
大哥的爱人
5楼-- · 2018-12-31 02:18

Here's another easy way to do

char str[100] ; 
sprintf(str , "%d" , 101 ) ;  
string s = str; 

sprintf is a well known one to insert any data into a string of required format .

You can convert char * array to string as shown in the third line.

查看更多
倾城一夜雪
6楼-- · 2018-12-31 02:19

I usually use the following method:

#include <sstream>

template <typename T>
  std::string NumberToString ( T Number )
  {
     std::ostringstream ss;
     ss << Number;
     return ss.str();
  }

described in details here.

查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 02:20

For C++98, there's a few options:

boost/lexical_cast

Boost is not a part of the C++ library, but contains many useful library extensions.

The lexical_cast function template offers a convenient and consistent form for supporting common conversions to and from arbitrary types when they are represented as text.
-- Boost's Documentation

#include "boost/lexical_cast.hpp"
#include <string>

int main() {
    int x = 5;
    std::string x_str = boost::lexical_cast<std::string>(x);
    return 0;
}

As for runtime, the lexical_cast operation takes about 80 microseconds (on my machine) on the first conversion, and then speeds up considerably afterwards if done redundantly.


itoa

This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
-- cplusplus.com

This means that gcc/g++ cannot compile code using itoa.

#include <stdlib.h>

int main() {
    int x = 5;
    char * x_str = new char[2];
    x_str = itoa(x, x_str, 10); // base 10
    return 0;
}

No runtime to report. I don't have Visual Studio installed, which is reportedly able to compile itoa.


sprintf

sprintf is a C standard library function that works on C strings, and is a perfectly valid alternative.

Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.
-- cplusplus.com

#include <stdio.h>

int main() {
    int x = 5;
    char * x_str = new char[2];
    int chars_written = sprintf(x_str, "%d", x);
    return 0;
}

The stdio.h header may not be necessary. As for runtime, the sprintf operation takes about 40 microseconds (on my machine) on the first conversion, and then speeds up considerably afterwards if done redundantly.


stringstream

This is the C++ library's main way of converting integers to strings, and vice versa. There are similar sister functions to stringstream that further limit the intended use of the stream, such as ostringstream. Using ostringstream specifically tells the reader of your code that you only intend to use the << operator, essentially. This function is all that's particularly necessary to convert an integer to a string. See this question for a more elaborate discussion.

#include <sstream>
#include <string>

int main() {
    int x = 5;
    std::ostringstream stream;
    stream << x;
    std::string x_str = stream.str();
    return 0;
}

As for runtime, the ostringstream operation takes about 71 microseconds (on my machine), and then speeds up considerably afterwards if done redundantly, but not by as much as the previous functions.


Of course there are other options, and you can even wrap one of these into your own function, but this offers an analytical look at some of the popular ones.

查看更多
登录 后发表回答