c++ - 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"。
解决方案
您正在std::cin
与>>
运营商一起使用。此运算符读取格式化输入(单词)而不是未格式化输入(行)。"the dagger"
您的程序不是读取,而是简单地读取"the"
,并将其留"dagger"
在输入缓冲区中以供以后使用。
要将未格式化的输入读取到choice
,请std::getline(std::cin, choice);
改用。
推荐阅读
- c# - 通过 System.Net.Http.HttpClient (ASP.NET MVC) 读取不成功的 HTTP 请求的响应
- android - 未安装 Google Play 服务的 Android Mobile Vision API 和 ML Kit
- c# - UWP FullTrustProcess 无法加载 dll
- c++ - 在同一端口上发送和接收 UDP
- python - 对单词和字符进行分组和分类
- json - 使用 ReactJS 在 if 条件下返回值
- javascript - 从客户端到服务器获取多个图像时面临的问题,foreach 循环存在问题
- reactjs - 如何在材料 ui 版本 0.20.0 中的 TableRowColumn 中嵌套 TableRows(版本很重要)?
- sparql - 查找 Wikidata 对象的所有超类(递归)
- android - 从相机捕获原始图像后,无法在 imageview 上加载原始图像。有没有办法解决这个问题?