Concatenate a string with a C ++ float

3

I have a problem when concatenating a string type variable with a float, I have the following:

float c1 = 0, c2 = 0, c3 = 0;
std::string best = "";

Then I use it in the following way:

best = "Imagen 1: " + c1;
best = "Imagen 2: " + c2;
best = "Imagen 3: " + c3;

However, it throws me the following errors:

../src/Test.cpp:91:24: error: invalid operands of types ‘const char [11]’ and ‘float’ to binary ‘operator+’
    best = "Imagen 1: "+c1;
                        ^
../src/Test.cpp:93:24: error: invalid operands of types ‘const char [11]’ and ‘float’ to binary ‘operator+’
    best = "Imagen 2: "+c2;
                        ^
../src/Test.cpp:95:24: error: invalid operands of types ‘const char [11]’ and ‘float’ to binary ‘operator+’
    best = "Imagen 3: "+c3;

How could I fix it?

    
asked by Juan Pinzón 01.11.2016 в 21:40
source

2 answers

2

In C ++ 11, you can use the to_string method like this:

best = "Imagen 1: " + std::to_string(c1);
best = "Imagen 2: " + std::to_string(c2);
best = "Imagen 3: " + std::to_string(c3);

Before C ++ 11, it could be done with stringstream :

#include <sstream>

std::stringstream ss;

ss << "Imagen 1: " << std::to_string(c1);
best = ss.str();

ss.str(std::string());

ss << "Imagen 1: " << std::to_string(c2);
best = ss.str();

ss.str(std::string());

ss << "Imagen 1: " << std::to_string(c3);
best = ss.str();

ss.str(std::string());

Or better said @ Peregring-lk, you can create a method to do it as much as you want:

#include <sstream>

std::string floatToString(const float& val) {
    std::stringstream ss;
    ss << val;
    return ss.str();
} 

best = "Imagen 1: " + floatToString(c1);
best = "Imagen 2: " + floatToString(c2);
best = "Imagen 3: " + floatToString(c3);
    
answered by 01.11.2016 / 21:47
source
2
#include <sstream>

std::ostringstream oss;
oss << c1;
best = "Imagen 1" + c1.str();

And so for each conversion you want to make. The best thing is to create your own method:

#include <sstream>

std::string f2string(const float& val)
{
    std::ostringstream os;

    os << val;

    return os.str();
}

best = "Imagen 1" + f2string(c1);
best = "Imagen 2" + f2string(c2);
best = "Imagen 3" + f2string(c3);
    
answered by 01.11.2016 в 21:58