Easiest way to convert int to string in C++

后端 未结 28 1791
甜味超标
甜味超标 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:18
    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;
    }
    
    0 讨论(0)
  • 2020-11-21 07:19

    This worked for me -

    My code:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int n = 32;
        string s = to_string(n);
        cout << "string: " + s  << endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-21 07:19

    Use:

    #include<iostream>
    #include<string>
    
    std::string intToString(int num);
    
    int main()
    {
        int integer = 4782151;
    
        std::string integerAsStr = intToString(integer);
    
        std::cout << "integer = " << integer << std::endl;
        std::cout << "integerAsStr = " << integerAsStr << std::endl;
    
        return 0;
    }
    
    std::string intToString(int num)
    {
        std::string numAsStr;
    
        while (num)
        {
            char toInsert = (num % 10) + 48;
            numAsStr.insert(0, 1, toInsert);
    
            num /= 10;
        }
        return numAsStr;
    }
    
    0 讨论(0)
  • 2020-11-21 07:20

    If you have Boost installed (which you should):

    #include <boost/lexical_cast.hpp>
    
    int num = 4;
    std::string str = boost::lexical_cast<std::string>(num);
    
    0 讨论(0)
  • 2020-11-21 07:20

    It would be easier using stringstreams:

    #include <sstream>
    
    int x = 42;          // The integer
    string str;          // The string
    ostringstream temp;  // 'temp' as in temporary
    temp << x;
    str = temp.str();    // str is 'temp' as string
    

    Or make a function:

    #include <sstream>
    
    string IntToString(int a)
    {
        ostringstream temp;
        temp << a;
        return temp.str();
    }
    
    0 讨论(0)
  • 2020-11-21 07:20
    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).

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