Easiest way to convert int to string in C++

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

    It would be easier using stringstreams:

    #include 
    
    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 
    
    string IntToString(int a)
    {
        ostringstream temp;
        temp << a;
        return temp.str();
    }
    

提交回复
热议问题