查找流为CIN和ifstream的结束?
题
我通过一个C ++课本,我有一个复习到C ++编程运行自己。其中的一个实际问题(没有考虑太多细节)要我定义可通过ifstream的或CIN的功能(例如istream的)作为参数。从那里,我必须通过流中读取。麻烦的是,我无法想出一个办法有这样的一个的功能将CIN和ifstream的有效发现流的末尾。即,
while(input_stream.peek() != EOF)
是不会工作CIN。我可以返工的功能,寻找一个特定词组(如“的流##结束”或某事),但我认为这是一个坏主意,如果我通过了文件流具有准确的词组。
我认为使用函数重载,但到目前为止,这本书已经提到,当它想我这样做。我可能把太多精力投入到这一做法的问题,但我很享受创作的过程,并很好奇,如果有这样的方式来做到这一点没有超载。
解决方案
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
(EOF可以与Windows和Ctrl-d按Ctrl-Z上许多其它操作系统生成)
其他提示
为什么不std::cin.eof()
工作?标准输入关闭时cin
将信号EOF,这将发生在与控制+ d (* nix中)或 CTRL + Z (Windows)中,或者(在用户信号,它可以传送输入流的情况下)时,管道的端部的文件
如果您在布尔上下文使用流,然后将自身转变为如果没有达到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).
}
不隶属于 StackOverflow