0
#include <iostream>
#include <cmath>
#include <string>
using namespace std;

string STRING;

     bool isEqual(double a, double b)
    {
        return  fabs(a-b) ==0;
    }

int main()
{
   STRING = isEqual(3,3); <--------HERE'S THE MAIN PROBLEM

cout << STRING;


    return 0;
}

I'm having trouble setting the output I get from a boolean, be it "true" or "1" equal to a String.Also is it possible to use boolalpha and combine it with "isEqual()" so I can just type

cout <<isEqual(3,3) and it gives me "true" 
instead of having to type "cout << boolalpha<<isEqual(3,3) everytime".
Cœur
  • 37,241
  • 25
  • 195
  • 267

4 Answers4

2
std::string s = isEqual(3,3) ? "true" : "false";

also: you should in isEqual not compare with 0 but with a small value like <0.00001

AndersK
  • 35,813
  • 6
  • 60
  • 86
1

Since isEqual() is returning a bool, you should simply be able to use it in line with boolalpha:

cout << boolalpha << isEqual(3,3);

Edit: I see you edited your question to exclude the above option. The answers in the thread below still apply:

Also: Converting bool to text in C++

Community
  • 1
  • 1
Justin ᚅᚔᚈᚄᚒᚔ
  • 15,081
  • 7
  • 52
  • 64
0

is it possible? yes, if you can change the return type of your function to a wrapper that has an implicit conversion to either bool or string.

but it isn't a good idea.

c++ is strongly typed. learn to make that work in your favor.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

You have a small problem in your code:

STRING = isEqual(3,3); <--------HERE'S THE MAIN PROBLEM

should be

STRING = isEqual(3,3); <--------THIS IS JUST WRONG, I'M TRYING TO ASSIGN A BOOLEAN TO A STRING

Why would you do this? I'm sure there are more elegant ways to do it. (presented in the answers). This is how I'd do it:

   bool areTheyEqual = isEqual(3,3);
   cout << boolalpha << areTheyEqual << endl;

or simply:

   cout << boolalpha << isEqual(3,3) << endl;
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625