Adding floats into a string

Hello the question I am trying to solve is:
Write function doFrac that returns a string representing a common fraction given its numerator and denominator as input arguments and also returns the decimal value of the function.

So far I have created this:

1
2
3
4
5
 void doFrac (float x, float y, string& frac, float& dec)
{
    frac = x + "/" + y;
    dec = x/y;
}


Trying to run this myself I find it is incorrect. The error received is:
error: invalid operands of types ‘float’ and ‘const char [2]’ to binary ‘operator+’
I have found an answer an answer online using stringstream but we have not been introduced to this yet.
Why does this not work, and how would you return the string including the two float variables(as beginner friendly as possible)?
Thanks!
1
2
3
4
5
void doFrac(int x, int y, std::string& rep, float& result)
{
    rep = std::to_string(x) + '/' + std::to_string(y) ;
    result = static_cast<float>(x) / y ;
} 


Where one must #include <string> .

Note that x and y should be integral values.
Last edited on
Topic archived. No new replies allowed.