Easiest way to convert int to string in C++

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

    Using stringstream for number conversion is dangerous!

    See http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ where it tells that operator<< inserts formatted output.

    Depending on your current locale an integer greater than 3 digits, could convert to a string of 4 digits, adding an extra thousands separator.

    E.g., int = 1000 could be convertet to a string 1.001. This could make comparison operations not work at all.

    So I would strongly recommend using the std::to_string way. It is easier and does what you expect.

    Updated (see comments below):

    C++17 provides std::to_chars as a higher-performance locale-independent alternative

提交回复
热议问题