帮助使用带有while循环的iostream [英] Help with using iostream with while loops

查看:95
本文介绍了帮助使用带有while循环的iostream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题,每当我提示用户输入整数特定的输入时,如果用户输入的内容不是整数,我的代码会提示用户在允许用户输入之前输入3次输入这是我非常简单的代码:

I am having an issue, whenever I prompt the user for an integer specific input, should the user type something that isn't an integer, my code will prompt the user to enter the input 3 times before allowing the user to enter the input.
Here is my very simple code:

int main()
{
	bool valid = false;
	bool bfail;
	int mStreetNum;
	while (!valid)
	{
		cout << "Enter street number: ";
		cin >> mStreetNum;
		bfail = cin.fail();
		if (bfail)
		{
			cin.clear();
			cin.ignore();
			continue;
		}

		valid = true;
	}

}





这是结果:



This are the results:

Enter street number: gef
Enter street number: Enter street number: Enter street number: edf
Enter street number: Enter street number: Enter street number: 12



如何在没有提示输入之前再次提示用户输入?我在visual studio c ++上,在安装了GNU g ++编译器的Windows 10 cmd和Linux机器上进行了测试。



我尝试过:



我尝试使用我的调试器试图弄清楚发生了什么,但由于某些原因它似乎在我故意输入非整数输入。我的代码很简单,我老老实实地困惑为什么会这样。


How do I prompt the user again their input without prompting multiple times before they can enter? I tested this on visual studio c++, on a windows 10 cmd with GNU g++ compiler installed and on Linux machine.

What I have tried:

I tried using my debugger to try and figure out what is going on, but it for some reason it seems to skip the cin after I purposely enter a non-integer input. My code is simple enough that I am honestly perplexed why does that.

推荐答案

尝试:

Try:
#include <iostream>
#include <limits>
using namespace std;

int main()
{
  bool valid = false;
  bool bfail;
  int mStreetNum;
  while (!valid)
  {
    cout << "Enter street number: ";
    cin >> mStreetNum;
    bfail = cin.fail();
    if (bfail)
    {
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
      continue;
    }
    valid = true;
  }
}


这篇关于帮助使用带有while循环的iostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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