C++ - 寻找"帮助"

Crj*_*rju -1 c++ function

好吧,所以我实际上已经用C++进行了一段时间的编程,但是我现在对可能非常明显的事情感到难过.我决定写一个基本的计算器以获得乐趣.加,减,乘,除,整数.正如你在下面看到的,我有一个名为choice的int变量,寻找1,2,3或4.一旦选择,它将调用相应的函数.但是,我决定我希望能够随时输入"帮助"来表示帮助.我怎样才能做到这一点?我知道我可以简单地选择一个字符串,但我觉得这只会在问题上设置一个绑定(对未来的问题没有帮助).我想随时抓住"帮助".但是,使用另一个if()语句来捕获"帮助"

请帮助我,我相信这很简单,但由于某种原因我无法弄清楚!

#include <iostream>

int firstnum;
int secondnum;

int multiplication(){
    std::cout << "Multiplication chosen. Please enter first number." << std::endl;
    std::cin >> firstnum;
    std::cout << "Please enter second number." << endl;
    std::cin >> secondnum;
    std::cout << "Your answer is: " << firstnum * secondnum << "." << std::endl;
}

int division(){
    std::cout << "Division chosen. Please enter first number." << std::endl;
    std::cin >> firstnum;
    std::cout << "Please enter second number." << std::endl;
    std::cin >> secondnum;
    std::cout << "Your answer is: " << firstnum / secondnum << "." << std::endl;
}

int addition(){
    std::cout << "Addition chosen. Please enter first number." << std::endl;
    std::cin >> firstnum;
    std::cout << "Please enter second number." << std::endl;
    std::cin >> secondnum;
    std::cout << "Your answer is: " << firstnum + secondnum << "." << std::endl;
}

int subtraction(){
    std::cout << "Subtraction chosen. Please enter first number." << std::endl;
    std::cin >> firstnum;
    std::cout << "Please enter second number." << std::endl;
    std::cin >> secondnum;
    std::cout << "Your answer is: " << firstnum - secondnum << "." << std::endl;
}

int main(){
    int choice;
    std::cout << "Calculator." << std::endl;
    std::cout << "Multiplication: 1. Division: 2. Addition: 3. Subtraction: 4. Help: help." << std::endl;
    std::cin >> choice;
    if(choice == 1){
        multiplication();
    }
    if(choice == 2){
        division();
    }
    if(choice == 3){
        addition();
    }
    if(choice == 4){
        subtraction();
    }

////if the user types "help" it will show help.

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 5

我只想将选择更改为std :: string

std::string   choice;
std::cin >> choice;

if (choice == "1")    { .... }
if (choice == "help") { .... }
Run Code Online (Sandbox Code Playgroud)

但我也会改变if语句结构.
而不是if statements我会使用地图的列表.将命令映射到函数调用.

#include <iostream>
#include <map>
#include <functional>

int one()
{
    std::cout << "one\n";
}
int two()
{
    std::cout << "two\n";
}

int main()
{
    std::map<std::string, std::function<int()> >     action = {{"one", one}, {"two", two}};

    auto act = action.find("one");
    act->second();

}
Run Code Online (Sandbox Code Playgroud)

  • @SydZ:为什么会这样? (3认同)