如何将用户输入与 with if 语句结合起来?

How do I combine user input with with if statements?

我正在制作程序。为了使程序正常运行,我需要知道如何将用户输入 (cin) 与 if 语句结合起来,例如:

start:
    (program)    
    cout << "What would you like to do?";
    if cin = "end" goto end;
    if cin = "redo" goto start;

end:
    return 0;

我知道这不是有效代码,但我希望您能理解我正在尝试做的事情。我需要知道如何在 C++ 中执行此操作,如果可能的话,如果不能,如何执行相同的操作。

此外,在 Batch 中,执行类似 :start: "bookmarks" 程序的操作,以便您可以执行 "GOTO start" 命令以跳回该程序。你如何在 C++ 中做到这一点?

这个问题有点含糊,但我会尽力帮助你。

首先读入一个字符串的代码是:

std::string input;
std::cin >> input;

(当然,这需要你包含#include <string>#include <iostream>)。

其次,C++支持goto和labels。但在大多数情况下,有更好、更健壮和更可维护的解决方案来表达你自己。您想了解有关 whilefor 循环的更多信息。

我希望这个回答能为您提供一些提示,告诉您从哪里开始。任何基础 C++ 书籍都会涵盖这些主题,如果你真的想自学 C++,你应该买一本。

这是一个涵盖您的问题的小例子:

#include <string>
#include <iostream>

int main( int, char ** )
{
    std::string input;

    while( true )
    {
        std::cout << "What would you like to do?" << std::endl;
        std::cin >> input;
        if( input == "redo" )
        {
            continue;
        }
        else if( input == "end" )
        {
            break;
        }
        else
        {
            std::cout << "Invalid input: " << input << std::endl;
        }
    }

    return 0;
}