C ++ IO流简介 [英] Introduction To C++ IO Streams

查看:175
本文介绍了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:


您可以通过测试读取结果来检测特定的读取或写入操作失败。例如,要检查是否从用户读取了有效的整数,您可以这样做:

You can detect that a particular read or write operation failed by testing the result of the read. For example, to check that a valid integer is read from the user, you can do this:



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




这是因为读操作返回一个引用到流。

This works because the read operation returns a reference to the stream.

我理解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流简介的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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