我为什么要在cin.ignore()之前用cin.clear()来清除cin? [英] Why should I do cin.clear() before cin.ignore() to flush cin?

查看:202
本文介绍了我为什么要在cin.ignore()之前用cin.clear()来清除cin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

附件是我的编程作业。我试图处理既不是预期的整数也不是EOF的输入。我注意到为避免无限循环,我必须在读取下一个输入之前清除cin,但是:



1.我不完全确定原因。是因为错误的输入只是放回到输入流中吗?



2.为什么cin.ignore()不足以阻止无限循环?



3.最让我困惑的是我无法区分

cin.clear()然后cin.ignore()和

cin.ignore()然后cin.clear()

显然只有前一个订单有效。但是流错误状态与转储流有什么关系呢?



  #include   <   iostream  >  
#include < iomanip >

使用 命名空间标准;

int main()
{
int NUM;

cout<< 请输入一个十进制数字:;
cin>> NUM;

while (!cin.eof())
{
if (!cin.fail())
{
cout<< 其十六进制格式为:<< setbase( 16 )<< num<< ENDL;
cout<< 其八进制格式为:<< setbase( 8 )<< num<< ENDL;
}
cout<< 请输入一个十进制数字:;
cin.clear();
cin.ignore(numeric_limits< streamsize> :: max(),' \ n');
cin>> NUM;
}

return 0 ;
}

解决方案

cin.ignore 流输入功能 [ ^ ]:它会从流中读取字符,在您的情况下,字符'\ n' 被读取(它不会将这些字符存储在任何地方,与其他输入函数不同,但它会检查并计算它们)。



引发错误标志,输入函数不读取任何字符(它们会其他一些内容 [ ^ ],但它们在这里不相关)。用 cin.clear()清除标志后,cin.ignore(或getline(cin,str)或cin.get()或任何其他输入)可以继续

Attached is my programming homework. I was trying to deal with inputs that are neither expected integers nor EOF. I noticed that to avoid infinite loops I had to flush out cin before reading next input, but:

1. I'm not entirely sure why. Is it because a wrong input is just put back into the input stream?

2. Why is cin.ignore() alone not enough to stop infinite loops?

3. What confuses me most is I can't tell the difference between
cin.clear() then cin.ignore() and
cin.ignore() then cin.clear()
Apparently only the former order works. But what does stream error state have to do with dumping a stream?

#include<iostream>
#include<iomanip>

using namespace std;

int main()
{
	int num;
	
	cout << "Please enter a decimal number: ";
	cin >> num;

	while (!cin.eof())
	{
		if (!cin.fail())
		{
			cout << "Its hexadecimal format is: " << setbase(16) << num << endl;
			cout << "Its octal format is: " << setbase(8) << num << endl;
		}
		cout << "Please enter a decimal number: ";
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
		cin >> num;
	}

	return 0;
}

解决方案

cin.ignore is a stream input function[^]: it reads characters from the stream until, in your case, the character '\n' is read (it doesn't store those characters anywhere, unlike other input functions, but it examines and counts them).

While any error flag is raised, input functions do not read any characters (they do a few other things[^], but they aren't relevant here). Once the flag is cleared with cin.clear(), cin.ignore (or getline(cin, str), or cin.get() or any other input) can proceed.


这篇关于我为什么要在cin.ignore()之前用cin.clear()来清除cin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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