首页 > 解决方案 > C++ - 如果循环内的语句不能正常工作

问题描述

我正在尝试使用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代码,然后循环回到"which do you take",然后立即选择"dagger"

标签: c++loopsif-statement

解决方案


您正在std::cin>>运营商一起使用。此运算符读取格式化输入(单词)而不是未格式化输入(行)。"the dagger"您的程序不是读取,而是简单地读取"the",并将其留"dagger"在输入缓冲区中以供以后使用。

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


推荐阅读