convert to string

What is another way I can convert this float into a string other than to_string?

1
2
3
4
5
 
 string s = to_string(Accountbalance); //I wanted to change balance into string
                string output=accountNumber+" "+ s+ " "+name;
                outData<<output;
                break;
1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <sstream>
#include <iostream>
int main()
{
    double Accountbalance = 47.50;
    std::ostringstream oss;
    if (oss << Accountbalance)
        std::string s = oss.str(); // conversion successful.
    else
        // handle conversion error.
}


The conversion happens during the << operator, which is why its return value is checked.
If the conversion fails, it will not go into the if.
Last edited on
You could use std::stringstream as shown. Another possibility is the sprintf() function.
http://www.cplusplus.com/reference/cstdio/sprintf/

But I'm curious, why not replace this:
1
2
3
4
    string s = to_string(Accountbalance); //I wanted to change balance into string
    string output=accountNumber+" "+ s+ " "+name;
    outData<<output;
    break;

with this:
1
2
    outData << accountNumber << " " << Accountbalance << " " << name;
    break;

Topic archived. No new replies allowed.