获取while循环以再次获取输入? (C ++) [英] Get a do while loop to getinput again? (C++)

查看:117
本文介绍了获取while循环以再次获取输入? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于初学者c ++在线的一些问题创建一个程序。我遇到了一个问题,试图做到这一点,我需要一些帮助



每当我通过do while循环一次它不会提示我再次输入?

谢谢



Hi, I'm trying to create a program based on some problems for beginner c++ online. I came across a problem trying to do this and I need some help

Whenever I go through the do while loop once it doesn't prompt me to input again?
Thanks

#include <iostream>
#include <string>

using namespace std;
int main() {
	string drinkChosen;
	string coke = "coke";
	string fanta = "fanta";
	string pepsi = "pepsi";
	string sprite = "sprite";
	string drpepper = "drpepper";
	string water = "water";
	int x;

	do {
	std::cout << "choose which beverage you would like" <<std::endl << "Coke, Fanta, Pepsi, Sprite or drpepper" << std::endl;
	

	getline(std::cin, drinkChosen);

		if (drinkChosen == coke) {

			std::cout << "you have chosen coke" << std::endl;

		}

		else if (drinkChosen == fanta) {

			std::cout << "you have chosen fanta" << std::endl;

		}

		else if (drinkChosen == pepsi) {

			std::cout << "you have chosen pepsi" << std::endl;

		}
		else if (drinkChosen == sprite) {

			std::cout << "you have chosen sprite" << std::endl;

		}
		else if (drinkChosen == drpepper) {

			std::cout << "you have chosen pepper" << std::endl;

		}
		else if (drinkChosen == water) {

			std::cout << "Please, you know you want a nice drink" << std::endl;

		}
		else {

			std::cout << "please choose again" << std::endl;
		}
		
		std::cout << "Please press 1 to confirm or zero to start again" << std::endl;
		std::cin >> x;
		
		
	} while (x == 0);

	
	
	

	system("pause");
	return 0;
}





我的尝试:



我试图移动string drinkChosen

我也搞乱了while循环的条件

我也搜索了这个网站,堆栈溢出



What I have tried:

I have tried to move around the "string drinkChosen"
I have also messed around with the while loop's conditions
I have also searched this website and stack overflow

推荐答案

这是因为在输入0或1后输入流中仍有一个行结束符。修改代码如下: br />
That is because there is still a line end character(s) in the input stream after you enter 0 or 1. Modify your code as follows:
std::cout << "Please press 1 to confirm or zero to start again" << std::endl;
std::cin >> x;
cin.get();



您还应该添加代码以将输入字符串转换为小写以进行相等测试。


You should also add code to convert the input strings to lower case for your equality tests.


这篇关于获取while循环以再次获取输入? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆