Easiest way to convert int to string in C++

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

提交回复
热议问题