gpt4 book ai didi

C++ While( cin >> x) 是如何工作的?

转载 作者:可可西里 更新时间:2023-11-01 17:41:57 26 4
gpt4 key购买 nike

我的问题是如何,

while(cin>>x)
{
//code
}

工作。或者更具体地说,该代码如何停止循环?

来自文档 here ,看起来 >> 运算符返回一个 &istream。这是否意味着如果读取失败或到达文件末尾,它不仅会设置 eofbit、failbit 或 badbit,还会返回空值?这真的没有意义,所以我怀疑是这样。

是否对 eofbit 进行某种隐式检查?

我问是因为我希望用这样的 2 个类实现类似的东西,

class B
{
//variables and methods
}

class A
{
//Variables and methods
//Container of B objects. ex. B[] or vector<B> or Map<key,B>
&A >> (B b);
}

int main()
{
A a;
B b;

while( a >> b)
{
//Code
}

}

注意:我不打算从 istream 继承,除非它是使这项工作变得神奇的地方。这样做的原因是我希望让类及其依赖项尽可能小。如果我从 istream 继承,我将收到它的所有公共(public)和 protected 东西,并且我不会尝试创建类似 istream 的对象。我只想复制一个真的不错的部分。

编辑: 我正在使用 Visual Studio 2010(这真的很痛苦),我需要一些与它的 C++03 + 一些 C++ 实现兼容的东西11.

最佳答案

From the documentation here, it looks like the >> operator returns a &istream. Does that mean if the read fails or hits the end of file it not only sets the eofbit, failbit or badbit but also returns a null?

不,返回对流对象的引用,但将设置内部标志。随后调用 operator>>仅测试这些标志后就会失败。

Is there some kind of implicit check of the eofbit?

不确定问题是什么。流不会尝试预先确定下一个请求是否会失败,而只会在一个操作因为遇到 EOF 而失败时设置标志。每次调用operator>>将首先测试流的状态,只有在流处于良好状态时才会继续。

How does while(cin>>x) work?

存在从流对象到 bool 值的隐式转换。转换产量 true如果流处于良好状态或 false否则。

关于C++ While( cin >> x) 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12923762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com