【问题标题】:Using an input string as a function name c++使用输入字符串作为函数名 c++
【发布时间】:2014-02-11 07:26:16
【问题描述】:

第一次发帖,请轻点。我已经开始自学 C++,因为我一直很感兴趣,而且它对以后的工作也很有用。

好的,所以我编写了一个非常基本的程序,可以根据用户输入进行加、减、乘或除。

我的问题是我可以使用来自用户的输入作为字符串并使用它来调用函数吗?

见下面的代码:-

#include <iostream>
#include <string>

using namespace std;

// Addition Function
int Add (int a, int b)
{
int r; //Result
r=a+b; //formula
return r; //return result of formula
}

// Subtraction Function
int Subtract (int a, int b)
{
int r; //Result
r=a-b; //formula
return r; //return result of formula
}

// Multiply Function
int Multiply (int a, int b)
{
int r; //Result
r=a*b; //formula
return r; //return result of formula
}

// Divide Function
int Divide (int a, int b)
{
int r; //Result
r=a/b; //formula
return r; //return result of formula
}

// Main
int main()
{
int ip1, ip2, z;
string option;


cout << "Enter first number: ";
cin >> ip1;
cout << "Enter second number: ";
cin >> ip2;
cout << "What would you like to do?, Please type an option (Options: Add, Subtract, Multiply, Divide)\n";
getline(cin,option);
z = option (ip1,ip2);
cout << "The result is " << z;
}

所以我要求用户输入一个选项,即添加,然后程序获取该字符串(添加)并使用它来调用添加函数。

目前我在编译时遇到“不匹配调用”(std::string {aka std::basic_string}) (int&, int&) 错误

任何帮助将不胜感激

谢谢 刘易斯

【问题讨论】:

  • 你可以有std::map&lt;std::string, std::function&lt;int(int,int)&gt;&gt;然后就做z = myMap[option](ip1, ip2);

标签: c++ notepad++


【解决方案1】:

您可以使用非常简单的if 条件树:

     if (option == "Add")         z = Add(ip1, ip2);
else if (option == "Subtract")    z = Subtract(ip1, ip2);
else if (option == "Multiply")    z = Multiply(ip1, ip2);
else if (option == "Divide")      z = Divide(ip1, ip2);

您也可以使用std::mapstd::string 映射到相应的函数指针。它可能更干净,但写起来肯定更长:

std::map<std::string, std::function<int(int, int)>> mapping;
mapping["Add"]      = &Add;
mapping["Subtract"] = &Subtract;
mapping["Multiply"] = &Multiply;
mapping["Divide"]   = &Divide;

if (mapping.find(option) == mapping.end())
    // there's no such an option
z = mapping[option](ip1, ip2);

在这种特殊情况下,您甚至可以不使用 std::function 而只使用 C 函数指针(对于非std::function 爱好者):

std::map<std::string, int(*)(int, int)> mapping;

请注意,您可以在函数声明中去掉很多代码行和临时变量:

int Add (int a, int b)      { return a + b; }
int Subtract (int a, int b) { return a - b; }
int Multiply (int a, int b) { return a * b; }
int Divide (int a, int b)   { return a / b; }

【讨论】:

  • 我想你的意思是std::function&lt;int(int, int)&gt;。不要称它为地图:P
  • 感谢您的所有帮助。我最后使用了 If 语句,因为它也使我能够使用 if 和 else 等......
猜你喜欢
  • 2012-10-05
  • 1970-01-01
  • 2017-12-11
  • 2012-07-12
  • 2020-03-19
  • 2018-06-26
  • 1970-01-01
  • 2019-11-23
  • 2014-12-15
相关资源
最近更新 更多