-3

Indeed I have this code :

#include <iostream>

double a(){return 1.23;}
double b(){return 1.21;}

int main(){
std::string function0;
return EXIT_SUCCESS;
}

And what I want is this : if function0 = 'a' I would like to be able to transform the string function0 in the function a but I don't know how to do this. If function0 is equals to b I would like to call the function b.

Thank you for your help !

2 Answers2

0

What you want to do is calling one of the functions depending on the value of the string variable. This is easily achievable.

  1. An if else construct in the main():

    if (function0 == "a") {
        foo = a();
    } else if (function0 == "b") {
        foo = b();
    }
    
  2. Merge the function and modify the result, so it behaves differently depending on the input:

    double newFunction (string input) {
         double valueForA = 1.23;
         double valueForB = 1.21;
    
         if (input == "a") {
             return valueForA;
         } else if (input == "b") {
             return valueForB;
         } else {
             //what if it's not "a" nor "b"?
             return 0;
         }
    }
    

    Usage:

    double foo = newFunction(function0);
    

N.B:

  1. Don't neglect the return values of your function, if the returned value is not important use void function.
  2. Learn to use variables (instead of useless functions). You could have created 2 variables in the main, and that would be it.
  3. Visit this link to get started with C++. Without good references, you'll hate learning it, and that would be sad, or would it?
  4. Stop using the book/website you're currently using to learn programming. It's (probably) garbage.
Community
  • 1
  • 1
Nhatz HK
  • 42
  • 2
  • 11
-1

function pointers may help.

double (*funcPtr)();
int main() {
  if (function0 == "a")
    funcPtr = &a;
  else 
    funcPtr = &b;

  (*funcPtr)(); //calling a() or b()
}
jsn
  • 71
  • 4
  • 1
    Considering how he put the tag c++11 and c++14, suggesting `std::function` would have been a better choice. – Rosme May 09 '17 at 21:21