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
  • 34,719
  • 24
  • 185
  • 251

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
  • 34,991
  • 6
  • 57
  • 84
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 ᚅᚔᚈᚄᚒᚔ
  • 14,744
  • 6
  • 50
  • 63
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
  • 269,602
  • 39
  • 394
  • 697
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
  • 245,575
  • 61
  • 446
  • 609