使用cin>>错误处理 [英] Using cin >> to error handle

查看:65
本文介绍了使用cin>>错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读中遇到了这个问题...

I came across this in my readings...

while(!(std::cin >> array[i])) 
{
std::cin.clear(); 
while(std::cin.get()!= '\n') 
continue; 
std::cout << "enter a new input: ";
}

而且,我不太了解错误处理的工作方式.使用了std::cin.clear(),但是代码继续从下一行的cin对象中获取字符,然后使用continue语句.如果不清除cin,clear到底会做什么?谢谢你.

And, I don't really understand how the error handling is working. std::cin.clear() is used but the code continues to get characters from the cin object in the next line and then uses a continue statement. What exactly does the clear do if it doesn't clear the cin? Thank you.

推荐答案

cin.clear()的作用是清除cin流的错误标志.这样做时,cin流的操作可以继续进行.流并返回它. 要了解循环的作用,请考虑以下情况:

what cin.clear() does is to clear the cin stream's error flags.When it does this cin stream operations can continue.the next line extracts a character from the stream and returns it. To understand what the loop does consider the following case :

假设该数组的类型为int,然后输入:abc,然后按Enter. cin标识字符串输入不能进入int数组.因此它返回false并设置错误标志.当您执行cin.clear()时,它将重置错误标志,以便可以继续进行进一步的操作(cin.get()可以工作).现在,cin.get()从溪流.因为它不等于'\ n',所以循环继续(第二个循环),直到提取出'\ n'=>,这意味着您刚刚输入的错误的I/P都被冲走了,您可以重新开始

Suppose the array is of type int and you enter:abc and then press enter. cin identifies that the string input cannot go into the int array. and so it returns false and sets the error flags.when you perform cin.clear() it resets the error flags so that further operartions can continue(cin.get() can work).Now cin.get() extracts a from the stream. since it is not equal to '\n' the loop continues(second loop) until it extracts '\n' => meaning the wrong i/p you just entered is all washed away u can start afresh

这篇关于使用cin&gt;&gt;错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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