C++ - 如果循环内的语句无法正常工作

标签 c++ loops if-statement

我正在尝试使用 std::cin同时有一个选项循环回到开始。循环运行完美,但是当我在其中一个 if 语句中添加一个额外的选项然后输入它时,它并不认为我选择的是一个选项。

#include <iostream>
#include <string>
#include <windows.h>
#include <chrono>
#include <thread>
using namespace std;

int main() {  
    string  choice;
    char restart;

    do {
        choice.clear();
        cout << "Which do you take? " << endl;
        cin >> choice;

        if (choice == "all") {
            //cout code
            restart = 'y';
        }
        else if (choice == "dagger" || choice == "the dagger") {
            choice.clear();
            cout << "You pick up the dagger" << endl << endl;
            return 0;
        }
        else {
            choice.clear();
            cout << "That isn't an option, pick again... "<< endl << endl;
            sleep_for(1s);
            restart = 'y';
        }

    } while (restart == 'y');
}

当我输入 “dagger” 时,它工作得很好,但是当我输入 “the dagger” 时,它说运行 else 代码,然后循环回到“你拿什么”,然后立即选择“ Dagger ”

最佳答案

您正在将 std::cin>> 运算符一起使用。此运算符读取格式化输入(字)而不是未格式化输入(行)。您的程序不是读取 “the dagger”,而是简单地读取 “the”,然后将 “dagger” 留在输入缓冲区中以备后用。

要将未格式化的输入读取到 choice,请改用 std::getline(std::cin, choice);

关于C++ - 如果循环内的语句无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689808/

相关文章:

c++ - 等价于 C++ 中的 printf ("%.4d",x)

c# - 表单未显示在凭据提供程序中

c++ - 检查哪个模块最接近

string - 如何在 Robot Framework 中搜索空字符串/比较两个字符串

c++ - "deque.h"中的 android-ndk-r7c 不合格 id 错误

c++ - 从 C++ 连接到 Windows 文件复制 API

javascript - jQuery setInterval 不循环

python - While 函数中的循环 (Python)

if-statement - Google Sheets ArrayFormula 用于比较多个不同行中的多个单元格

java - 为什么两个相等的字符串不匹配?