Convert a float or an integer to string in c ++

2

I wanted to know a simple way to convert a variable float or int in data type string in C++ . Because look in several places and talk about using sprintf , from the library stdio.h but it does not work with string but with char .

For example, to a number 1564.53 I want to pass it to "1564.53" but I want that string not to be lost but saved in a variable of type string .

For what I need is to return a balance in currency format, that is, with the sign $ pesos at the beginning followed by the value of the balance, but this is in float .

    
asked by Emiliano Calvacho 21.04.2018 в 16:36
source

3 answers

3

As of C++ 11 , the standard library of C++ provides the function std::to_string(arg) with several compatible types for arg , and if you can accept the default format (%f) .

Or alternatively you can use ostringstream from <sstream> , although it may not be the easiest way.

#include <sstream>
std::string Convert (float number){
    std::ostringstream buff;
    buff<<number;
    return buff.str();   
}
  

Source: Conversion of Float to Chain

Additionally If you agree with Boost, lexical_cast < > It is a convenient alternative:

std::string s = boost::lexical_cast<std::string>(tuFloat);

Efficient alternatives are, for example, FastFormat or simply C-style features.

    
answered by 21.04.2018 / 16:56
source
1

Try this:

int Number = 123;
string String = static_cast<ostringstream*>( &(ostringstream() << Number) )->str();
    
answered by 21.04.2018 в 16:43
1
  

J. Rodríguez

As the colleague says. It works perfect

This way you can use it.

#include <iostream>
#include <sstream>
using namespace std;


std::string Convert (float number){
    std::ostringstream buff;
    buff<<number;
    return buff.str();
}

int main(){
    float Num;
    cout << "Ingrese un numero : ";
    cin >> Num;

    cout << endl << "Numero digitado es: " << Num;
    // Puedes hacerlo asi, aunque no quieres eso creo
    cout << endl << "Numero digitado es: $" << Num;

    // Ahora convertir
    string NumeroString = Convert(Num);
    cout << endl << "String :" << NumeroString;

    NumeroString = "$" + NumeroString;
    cout << endl << "String :" << NumeroString;

    return 0;
} 
    
answered by 21.04.2018 в 20:16