Easiest way to convert int to string in C++

后端 未结 28 1787
甜味超标
甜味超标 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:13

    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 << (const T& x) {
            s << x; return *this;
        }   
        operator std::string() {return s.str();}
    };
    

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

    Example:

    #include 
    
    int main() {
        std::string x =
          strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
        std::cout << x << std::endl;
    }
    

提交回复
热议问题