Easiest way to convert int to string in C++

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

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 

回答1:

C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.

#include    std::string s = std::to_string(42); 

is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:

auto s = std::to_string(42); 

Note: see [string.conversions] (21.5 in n3242)



回答2:

Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:

#include   #define SSTR( x ) static_cast( \         ( std::ostringstream() 

Usage is as easy as could be:

int i = 42; std::cout 

The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast); both these other solutions have a better performance though.



回答3:

I usually use the following method:

#include   template    std::string NumberToString ( T Number )   {      std::ostringstream ss;      ss 

described in details here.



回答4:

Probably the most common easy way wraps essentially your second choice into a template named lexical_cast, such as the one in Boost, so your code looks like this:

int a = 10; string s = lexical_cast(a); 

One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).

Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it's substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn't be converted to an int (e.g., 1234 would succeed, but 123abc would throw).

As of C++11, there's a std::to_string function overloaded for integer types, so you can use code like:

int a = 20; std::string s = to_string(a); 

The standard defines these as being equivalent to doing the conversion with sprintf (using the conversion specifier that matches the supplied type of object, such as %d for int), into a buffer of sufficient size, then creating an std::string of the contents of that buffer.



回答5:

If you have Boost installed (which you should):

#include   int num = 4; std::string str = boost::lexical_cast<:string>(num); 


回答6:

Wouldn't it be easier using stringstreams?

#include   int x=42;            //The integer string str;          //The string ostringstream temp;  //temp as in temporary temp

Or make a function:

#include   string IntToString (int a) {     ostringstream temp;     temp


回答7:

Not that I know of, in pure C++. But a little modification of what you mentioned

string s = string(itoa(a)); 

should work, and it's pretty short.



回答8:

sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.



回答9:

First include:

#include  #include 

Second add the method:

template  string NumberToString(T pNumber) {  ostringstream oOStrStream;  oOStrStream 

Use the method like this:

NumberToString(69); 

or

int x = 69; string vStr = NumberToString(x) + " Hello word!." 


回答10:

You can use std::to_string available in C++11 as suggested by Matthieu M.:

std::to_string(42); 

Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::FormatInt from the C++ Format library to convert an integer to std::string:

fmt::FormatInt(42).str(); 

Or a C string:

fmt::FormatInt f(42); f.c_str(); 

The latter doesn't do any dynamic memory allocations and is more than 10 times faster than std::to_string on Boost Karma benchmarks. See Fast integer to string conversion in C++ for more details.

Unlike std::to_string, fmt::FormatInt doesn't require C++11 and works with any C++ compiler.

Disclaimer: I'm the author of the C++ Format library.



回答11:

Using stringstream for number conversion is dangerous!

See http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ where it tells that operator inserts formatted output.

Depending on your current locale an integer greater than 3 digits, could convert to a string of 4 digits, adding an extra thousands separator.

E.g., int = 1000 could be convertet to a string 1.001. This could make comparison operations not work at all.

So I would strongly recommend using the std::to_string way. It is easier and does what you expect.



回答12:

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   int main() {     int x = 5;     std::string x_str = boost::lexical_cast<: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   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   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  #include   int main() {     int x = 5;     std::ostringstream stream;     stream 

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.



回答13:

namespace std {     inline string to_string(int _Val)     {   // convert long long to string         char _Buf[2 * _MAX_INT_DIG];         snprintf(_Buf, "%d", _Val);         return (string(_Buf));     } } 

you can now use to_string(5)



回答14:

Use:

#define convertToString(x) #x  int main() {     convertToString(42); // Returns const char* equivalent of 42 } 


回答15:

I use:

int myint = 0; long double myLD = 0.0;  string myint_str = static_cast( &(ostringstream() str(); string myLD_str = static_cast( &(ostringstream() str(); 

It works on my windows and linux g++ compilers.



回答16:

Using CString:

int a = 10; CString strA; strA.Format("%d", a); 


回答17:

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


回答18:

It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way

#include  #include   struct strmake {     std::stringstream s;     template  strmake& operator 

Now you may append whatever you want (provided that an operator is defined for it) to strmake() and use it in place of an std::string.

Example:

#include   int main() {     std::string x =       strmake() 


回答19:

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.



回答20:

char * bufSecs = new char[32]; char * bufMs = new char[32]; sprintf(bufSecs,"%d",timeStart.elapsed()/1000); sprintf(bufMs,"%d",timeStart.elapsed()%1000); 


回答21:

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) 

If you are converting a three-digit number:

*(int32_t*)s = 0x303030 | (n/100) | (n/10%10) 

If you are converting a four-digit number:

*(int64_t*)s = 0x30303030 | (n/1000) | (n/100%10)

And so on up to seven-digit numbers :)



回答22:

You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.

  • You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.

    • If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
      keep doing it until no more numbers in position 100,000. Drop another power of ten

    • If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
      keep doing it until no more numbers in position 10,000.

  • Drop another power of ten

  • Repeat pattern

I know 950 is too small to use as an example but I hope you get the idea.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!