3

I understand that to use ctrl-z to signal EOF or EOT is generally outdated and not recommended, but I'm just curious about what's happening under the hood.

Say I have something like this in C++:

#include <iostream>
#include <string>

int main() {
    while (!cin.eof()) {
        string str;
        getline(cin, str);
    }
    cout << "out of while" << endl;
    return 0;
}

If I do abc[^Z][newline], the program still runs. Same for abc[^D][newline].

But if I input a line purely contains [^Z][newline], the program exists properly.

I understand it's likely that it's OS specific but I'm just curious about what's going on there.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Boyang
  • 2,520
  • 5
  • 31
  • 49
  • Windows/DOS is not famous for being useful in the command-line. Try asking the Cygwin/MSYS folks about their experience trying to make programs behave both on bash and cmd.exe. By the way, `while (!cin.eof())` is bad form; wouldn't change your results, but in almost every case it's incorrect. – DanielKO Oct 15 '13 at 04:32

1 Answers1

1

First off, this article has some excellent insight into Ctrl-Z (DOS / Windows) and Ctrl-D (UNIX / Linux): http://latedev.wordpress.com/2012/12/04/all-about-eof/

It's well worth reading. It also points out an issue with your while-loop above.

Most importantly, Ctrl-Z does not indicate EOF. However, when it is the first character on the line, most Windows programs reading from console recognize that as the end of input. The result is effectively an EOF on cin. Indeed, files opened in text mode may behave the same way, although nothing in the C++ standard requires them to.

Note that historically, Ctrl-Z for end-of-input must be at the start of the line. Ctrl-Z elsewhere on the line doesn't have the same effect.

Joe Z
  • 17,413
  • 3
  • 28
  • 39