Easiest way to convert int to string in C++

后端 未结 28 1790
甜味超标
甜味超标 2020-11-21 06:42

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)



        
相关标签:
28条回答
  • 2020-11-21 07:24
    char * bufSecs = new char[32];
    char * bufMs = new char[32];
    sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
    sprintf(bufMs, "%d", timeStart.elapsed()%1000);
    
    0 讨论(0)
  • 2020-11-21 07:26

    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.

    0 讨论(0)
  • 2020-11-21 07:28

    int i = 255; std::string s = std::to_string(i);

    In c++, to_string() will create a string object of the integer value by representing the value as a sequence of characters.

    0 讨论(0)
  • 2020-11-21 07:29

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

    0 讨论(0)
  • 2020-11-21 07:29

    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<string>(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 = std::to_string(a);
    // or: auto s = std::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.

    0 讨论(0)
  • 2020-11-21 07:31

    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.

    0 讨论(0)
提交回复
热议问题