本文介绍了C ++ IO流简介的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从获得了一段代码,我很困惑关于它是如何工作的?该代码段首先说:

I got a snippet of code from this article and I'm confused as to how it works? The snippet starts by saying:



int x;
if ( cin >> x )
{
    cout << "Please enter a valid number" << endl;
}



我理解cin >> x操作返回对cin的引用,但我仍然困惑评估对标准输入流对象的引用允许您检查输入是否为有效整数。

I understand that the cin >> x operation returns a reference to cin but I'm still confused as to how evaluating the reference to the standard input stream object allows you to check that the input is a valid integer.

推荐答案

cin istream 模板类的实例。 operator>> 会对此istream实例执行操作,以将输入加载到数据中,并返回对此 istream 的引用。然后在 while 条件下,通过调用 cin :: operator void *()const 显式运算符bool()const 在C ++ 11中)调用 fail()函数来测试操作是否成功。这就是为什么你可以在条件下使用这个操作

cin is an instance of istream template class. operator >> acts on this istream instance to load input into data and returns a reference to this istream. Then in while condition it is tested by a call to cin::operator void*() const (explicit operator bool() const in C++11) which invokes fail() function to test if operation succeeded. This is why you can use this operation in while condition

while ( cin >> x)
{
   //...

这篇关于C ++ IO流简介的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 23:01