简体   繁体   English

EOF在Windows上不是总是^ Z吗?

[英]EOF is not always ^Z on Windows?

#include <iostream>
using namespace std;

int main()
{
    int x;
    cin >> x;
    if (x == EOF)
        cout << x;
    system("pause");
}

Inputting the EOF on Windows output nothing. 在Windows上输入EOF不会输出任何内容。 While -1 outputs -1. 而-1输出-1。

Over here 在这里

#include <iostream>
using namespace std;

int main()
{
    int x;
    if ((x=cin.get()) == EOF)
        cout << x;
    system("pause");
}

Inputting the EOF on Windows outputs -1. 在Windows上输入EOF将输出-1。 While -1 outputs nothing. -1则什么也不输出。

Now I am totally confused (I am working on 64-bit Windows 7 with Visual Studio 2015; though I do not think this is related) 现在我完全感到困惑(我正在使用Visual Studio 2015在64位Windows 7上工作;尽管我认为这没有关系)

I also want to add if "x" is assigned EOF in both cases, from where the difference came? 我还想补充一下,如果在两种情况下均分配了“ x”作为EOF,差异是从哪里来的? I am comparing the value of "x" to EOF in both cases, right? 在两种情况下,我都将“ x”的值与EOF进行比较,对吗?

EOF is a macro that expands to a negative int (usually -1 ). EOF是一个扩展为负int(通常为-1 )的宏。

This is a number returned by some input functions to indicate that an end-of-file occurred. 这是一些输入函数返回的数字,指示发生文件结尾。 It is nothing to do with the way that the end-of-file condition was triggered by your operating system (be it pressing ^Z, or running out of input, or whatever). 文件结束条件是由操作系统触发的(与按^ Z或输入用完之类的东西无关 )。

The code: 编码:

int x;
cin >> x

performs formatted input . 执行格式化的输入 The >> and << operators are for formatted I/O. >><<操作符用于格式化的I / O。 It means to read a textual representation of a number and convert that to int . 这意味着读取数字的文本表示形式并将其转换为int The only way you will get x == -1 is if you actually type in -1 , as you have found. 如您所知,获得x == -1的唯一方法是实际输入-1

To detect whether end-of-file occurred you can inspect the stream via cin.eof() after doing the read. 要检测是否发生文件结尾,可以在读取后通过cin.eof()检查流。 (Note that normally you should check for all failure modes , not just end-of-file). (请注意,通常应检查所有故障模式 ,而不仅仅是文件结尾)。

This code: 这段代码:

if ((x=cin.get()) == EOF)

will match if end-of-file occurred, because istream::get() is one of those few functions that indicates an end-of-file condition via the value returned. 如果发生文件结尾,则将匹配,因为istream::get()是少数几个通过返回的值指示文件结束条件的函数之一。 Again however, you are outputting the value of the EOF macro, which is unrelated to what you did in your operating system to generate the end-of-file condition. 但是,您再次输出EOF宏的值,该值与您在操作系统中生成文件结束条件所执行的操作无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM