![]() |
VOOZH | about |
In C++, converting numbers to strings is a very common task, especially while working with user input, file handling, and competitive programming problems. Sometimes we need to convert an integer into a string for concatenation, formatting, or digit manipulation.
123
Explanation: The to_string() function converts the integer 123 into the string "123".
C++ provides multiple methods to convert a numeric value into a string. Some methods are modern and simple, while others are useful for older compilers or special formatting needs.
The to_string() function can be used to convert an integer, floating point values, or any number to a string. This function accepts a number(which can be any data type) and returns the number as the desired string.
Syntax:
string to_string(data_type value);
The integer in string is : 20 The float in string is : 30.500000
In this method, a string stream declares a stream object which first inserts a number, as a stream into an object and then uses "str()" to follow the internal conversion of a number to a string.
Syntax:
stringstream_object << value;
string_variable = stringstream_object.str();
Parameters
Return Type
The newly formed string from number is : 2016
sprintf() function stores the output on the char buffer specified in the function, instead of printing the output on the console.
Syntax:
sprintf(char_array, "format_specifier", value);
Parameters
Return Type
the string is : 12234
Similar to string conversion, the " lexical_cast() " function remains the same, but in the 'boost lexical cast' time argument list modifies to "lexical_cast(numeric_var).
Syntax:
lexical_cast<string>(value);
Parameters
Return Type
The float value in string is : 10.5 The int value in string is : 17
| Method | Advantages | Disadvantages |
|---|---|---|
| to_string() | Simple and fast | Requires C++11 or later |
| stringstream | Flexible and safe | Slightly slower |
| sprintf() | Works in older C/C++ | Less type-safe |
| boost::lexical_cast | Easy conversion | Requires Boost library |