Convert int to a string in C++

273次阅读

This post will discuss how to convert int to a string in C++.

1. Using std::to_string function

The most common and efficient way is to use the std::to_string function introduced with C++11, which returns a string representation of the specified value. It is overloaded for all data types.

We can also use std::to_wstring, which returns std::wstring.

 

 

Download  Run Code

Output:

10

2. Using string streams

Another good alternative is to use the stringstream to convert between strings and other data types. The idea is to insert a given integer into the stream and then write contents of its buffer to the std::string using its str() function. We need to include the <sstream> header file for this.

 

 

Download  Run Code

Output:

10

3. Using boost lexical_cast

We can also use the boost lexical_cast library for converting an int to a string in C++. Please note that this solution is just a less-verbose alternative to the previous approach as lexical_cast uses streams behind the scenes.

 

 

yiywain
版权声明:本站原创文章,由 yiywain 2022-08-25发表,共计1403字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。