而(文件> x)和文件结束问题 [英] while (cin >> x) and end-of-file issues

查看:87
本文介绍了而(文件> x)和文件结束问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,因为发生了什么,我正在使用一些程序从加速C ++,并有一个早期的程序的问题(第35页,如果你碰巧有一个副本

  while(cin) >> x){
++ count;
sum + = x;
}

(count是整数,x / p>

它的工作原理,允许我输入几个值,并将它们添加在一起,但我无法弄清楚文件结束信号发生了什么问题。这本书说,循环将继续运行,直到程序遇到文件结束信号,这是ctrl + z在Windows中。



这一切都很好,但是我的程序不会让我再次使用cin。我通常只是设置一个程序等待一些随机变量,以便在执行后立即停止控制台关闭(是否有更好的方法来做到这一点?)这是我注意到这一点,我想知道如果有解决方案。我已经做了一堆搜索,但发现没有说什么在书中已经说过(按ctrl + z,或输入不兼容的类型的输入等。)



我使用Visual studio 2008 express编译。

解决方案

从一个角度来看, '



但是,在一个输入流的末尾,输入流的结尾没有任何内容,所以尝试再次读取它是没有意义的。 'end-of-stream'实际上是一个特殊的字符,如Ctrl-Z在窗口上,我们知道有可能我们可以从 cin 。但是,失败的读取将导致流上的 eof 标记被设置。



清除此标记(和所有其他失败标志),您可以使用 clear 方法。

  std :: cin.clear(); 

调用此项后,您可以尝试另一次读取。


I'm a little confused as to what's going on, i'm playing with some programs from "Accelerated C++", and have hit a problem with one of the early programs (page 35, if you happen to have a copy nearby).

It uses this snippet:

while (cin >> x) {
   ++count;
   sum += x;
}

("count" is an integer, "x" is a double)

It works as intended, allowing me to enter several values and add them together, but i can't work out what's going wrong with "End-of-file" signalling. The book says the loop will keep running until the program encounters an end of file signal, which is ctrl+z in windows.

This is all fine, and works, but then my program won't let me use cin again. I usually just set up a program to wait for some random variable in order to stop the console closing immediately after executing (is there a better way to do that, by the way?) which is how i noticed this, and i'm wondering if there's a solution. I've done a bunch of searching, but found little that doesn't say what's already said in the book (press ctrl+z, or enter a non-compatible type of input etc.)

I'm using Visual studio 2008 express to compile.

解决方案

From one point of view, once you've hit the end of an input stream then by definition there's nothing left in the stream so trying to read again from it doesn't make sense.

However, in the case of 'end-of-stream' actually being caused be a special character like Ctrl-Z on windows, we know that there is the possibility that we could read again from cin. However, the failed read will have caused the eof flag on the stream to be set.

To clear this flag (and all the other failure flags) you can use the clear method.

std::cin.clear();

After calling this, you can attempt another read.

这篇关于而(文件> x)和文件结束问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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