2010-08-30 57 views
7

我正在运行自己的C++文本书,作为C++编程的回顾。其中一个实践问题(没有详细说明)要我定义一个可以通过ifstream或cin(例如istream)作为参数的函数。从那里,我必须通过流。麻烦的是,我找不到一种方法让这个的一个函数使用cin和ifstream来有效地找到流的结尾。即,查找cin&ifstream的流结束符?

while(input_stream.peek() != EOF) 

不会为cin工作。我可以修改函数来查找特定的短语(比如“#End of Stream#”或某物),但是如果我传递的文件流具有这个确切短语,我认为这是一个坏主意。

我曾经想过使用函数重载,但是到目前为止,本书提到了它希望我这样做的时候。我可能在这个练习题上付出了太多的努力,但我喜欢这个创造性的过程,并且很好奇,如果有这样一种方法可以做到这一点而不会超载。

+0

检查这个问题:http://stackoverflow.com/questions/3197025/end-of-fileeof-of-standard-input -stream-stdin – Archie 2010-08-30 18:23:12

回答

4

eof()确实为cin工作。你做错了什么;请发布您的代码。一个常见的绊脚石是eof标志被设置为之后您尝试读取流结束后面。

下面是一个示范:

#include <iostream> 
#include <string> 

int main(int, char*[]) 
{ 
    std::string s; 
    for (unsigned n = 0; n < 5; ++n) 
    { 
     bool before = std::cin.eof(); 
     std::cin >> s; 
     bool after = std::cin.eof(); 
     std::cout << int(before) << " " << int(after) << " " << s << std::endl; 
    } 

    return 0; 
} 

和其输出:

D:>t 
aaaaa 
0 0 aaaaa 
bbbbb 
0 0 bbbbb 
^Z 
0 1 bbbbb 
1 1 bbbbb 
1 1 bbbbb 

+0

对不起,我最初有while(!input_stream.eof()),但后来意识到我写了while(input_stream.peek!= EOF),而不是。无论如何,这两种方法都可以使用control + z(具有讽刺意味的是,我只是读了wikipedia中的eof字符)。感谢atzz帮助,以及每个人! – user435219 2010-08-30 18:37:00

+0

首选将流转换为'.eof'或'.bad'上的布尔值。 – 2012-05-02 17:45:23

2

为什么std::cin.eof()不工作? cin将在标准输入关闭时发出EOF信号,当用户使用Ctrl + d(* nix)或Ctrl + z(Windows)或(在管道输入流的情况下)文件结尾

+1

在Windows中是“Ctrl + Z”,“Ctrl + D”是基于UNIX的系统。 – Archie 2010-08-30 18:25:34

+0

@Archie哦,好点;补充说,在 – 2010-08-30 18:27:56

+0

啊,这确实工作(无论如何,以及Ctrl + Z的Windows)。对不起,如果我之前在(post_stream.eof())中有一些混淆,并且将它编辑为while(input_stream.peek()!= EOF)。无论如何,我关心的一点是while(!input_stream.eof())是当函数读取EOF字符时,为input_stream设置失败位。这是否应该发生? – user435219 2010-08-30 18:30:36

3
(EOF可以用Ctrl-Z上许多其他操作系统的Windows和Ctrl-d产生的)

如果您在布尔上下文中使用流,那么它会将自身转换为等于true的值(如果尚未达到EOF),并且如果尝试读取EOF(不是它)如果从流中读取以前的错误,也是错误的)。

由于流上的大多数IO操作都返回流(因此它们可以链接)。您可以进行读取操作并在测试中使用结果(如上所述)。

所以一个程序从流中读取数字流:

int main() 
{ 
    int x; 

    // Here we try and read a number from the stream. 
    // If this fails (because of EOF or other error) an internal flag is set. 
    // The stream is returned as the result of operator>> 
    // So the stream is then being used in the boolean context of the while() 
    // So it will be converted to true if operator>> worked correctly. 
    //       or false if operator>> failed because of EOF 
    while(std::cin >> x) 
    { 
     // The loop is only entered if operator>> worked correctly. 
     std::cout << "Value: " << x << "\n"; 
    } 

    // Exit when EOF (or other error). 
}