C ++中的递归函数,布尔语句和输入

时间:2017-07-20 20:21:46

标签: c++ recursion input boolean

我在C ++中创建一个Text RPG作为一个小项目。但是,如果用户输入"否"我无法重复我的功能。或无效的输入。

这是我的功能:

void name_type() {
    bool running = true;
    system("CLS");
    while (running == true) {
        std::string name, option;
        std::cout << "What is your name?\n";
        std::getline(std::cin, name);

        // Up to here is not repeated.

        system("CLS");
        std::cout << "Are you sure this is your name?\n\nType 'Yes' if so.\nElse, type 'No'.\n";
        std::cin >> option;

        system("CLS");
        if (option == "Yes" || option == "yes") {
            std::cout << "Hello, " << name << "!\n";
            running = false;
        }
        else if (option == "No" || option == "no") {
            continue;
        }
        else {
            continue;
        }
    }
}

问题在于,当我通过该功能时,如果我键入&#34; no&#34;,它只会在评论后重复任何内容。但是,如果我键入&#34;是&#34;,它可以正常工作。

任何人都可以解释发生了什么,以及如何解决它?

2 个答案:

答案 0 :(得分:1)

我看到如果他/她键入“否”或“否”,则继续将用户保留在名称选择循环中。为什么不检查是的呢?

bool running = true;   // initialize 'running' to true
std::string name, option;
std::cout << "What is your name?\n";
std::getline(std::cin, name);

system("CLS");
std::cout << "Are you sure this is your name?\n\nType 'Yes' if so.\nElse, type 'No'.\n";

while(running == true){    // outer loop
   std::cin >> option;  // read in the option
   while (!(option == "Yes" || option == "yes" )) {  // inner loop
      system("CLS");
      if (!(option == "No" || option == "no" )) {
         std::cout << "Invalid Input : Please enter Yes/No\n";
      }
      std::cout << "Are you sure this is your name?\n\nType 'Yes' if so.\nElse, type 'No'.\n";
   }  // check if the input is yes. if not, keep looping.
   running = false; // if the input was yes, set running to false and exit the outer loop
}

除非用户说“是”或“是”,否则应覆盖除“是”以外的任何输入。

答案 1 :(得分:1)

标准输入流留下了在输入“否”或“否”后按“输入”时创建的\ n(新行)。 因此,getline会立即读取一个空行,然后在此之后清除屏幕。这使得代码的印象不再重复。

您可以使用cin.ignore清除该新行的流。 另外,在打印邮件时,您可能需要考虑使用std :: endl而不是\ n。

void name_type() {
    bool running = true;
    system("CLS");
    while (running) {
        std::string name;
        std::cout << "What is your name?" << std::endl;
        std::getline(std::cin, name);

        std::string option;
        system("CLS");
        std::cout << "Are you sure this is your name?" << std::endl;
        std::cout << "Type 'Yes' if so." << std::endl;
        std::cout << "Else, type 'No'." << std::endl;
        std::cin >> option;
        std::cin.ignore(1, '\n');

        system("CLS");
        if (option == "Yes" || option == "yes") {
            std::cout << "Hello, " << name << "!" << std::endl;
            running = false;
        }
    }
}