简体   繁体   中英

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. While -1 outputs -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. While -1 outputs nothing.

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)

I also want to add if "x" is assigned EOF in both cases, from where the difference came? I am comparing the value of "x" to EOF in both cases, right?

EOF is a macro that expands to a negative int (usually -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).

The code:

int x;
cin >> x

performs formatted input . The >> and << operators are for formatted I/O. It means to read a textual representation of a number and convert that to int . The only way you will get x == -1 is if you actually type in -1 , as you have found.

To detect whether end-of-file occurred you can inspect the stream via cin.eof() after doing the read. (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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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