TO_STRING()

This function used to convert numeric values into their string representation. It supports integral types (int, long, long long, unsigned variants) and floating-point types (float, double, long double). It returns a std::string containing the textual form of the number, making it useful for output formatting, displaying values, logging, constructing strings dynamically, or preparing data for storage and transmission. Compared to alternatives like std::ostringstream, to_string() offers a straightforward, single-function conversion without needing to manage streams.

string strValue = to_string(value);  
// Converts value (int, float, double, etc.) to a string
#include <iostream>     // For input and output
#include <string>
using namespace std;

int main() {
    int intValue = 42;                  // Integer value
    float floatValue = 3.14159;         // Float value
    double doubleValue = 2.718281;      // Double value

    string intString = to_string(intValue);         // Convert int to string
    string floatString = to_string(floatValue);     // Convert float to string
    string doubleString = to_string(doubleValue);   // Convert double to string

    cout << "Integer as string: " << intString << endl;
    cout << "Float as string: " << floatString << endl;
    cout << "Double as string: " << doubleString << endl;

    return 0;  // End of program
}

Last updated