Convert Int/float/double Into a String in C++

Recipe # | posted in Howto, Programming | Comments

1 – Problem Description

A simple technique to convert an int/float/double to a string in C++, avoiding sprintf

2 – Solution

Use the following technique

#include <sstream> // Include this in the source file
#include <iostream> 

int main()
{
        int i = 10; // Could be float/double
        std::string strFromInt;
        std::stringstream out;
        out << i;
        strFromInt = out.str();

        std::cout << "strFromInt: " << strFromInt << "\n";

        return 0;
}       

Comments