为什么在Windows控制台程序中按Ctrl + Z时有时仅终止输入? [英] Why is input only sometimes terminated when I press Ctrl+Z in a Windows console program?

查看:245
本文介绍了为什么在Windows控制台程序中按Ctrl + Z时有时仅终止输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解使用ctrl-z发出EOF或EOT信号通常已过时,不建议使用,但我只是对引擎盖下发生的事情感到好奇.

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.

说我在C ++中有这样的东西:

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;
}

如果我执行abc [^ Z] [newline],程序仍将运行.与abc [^ D] [newline]相同.

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

但是如果我输入仅包含[^ Z] [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.

推荐答案

首先,本文对Ctrl-Z(DOS/Windows)和Ctrl-D(UNIX/Linux)有很好的了解:

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/

非常值得一读.它还指出了您上面的while循环存在的问题.

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

最重要的是,Ctrl-Z并不表示EOF.但是,当它是该行的第一个字符时,大多数从控制台读取的Windows程序都将其识别为输入的结尾.结果实际上是cin上的EOF.实际上,尽管在C ++标准中没有要求,但以文本模式 打开的文件的行为可能相同.

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.

请注意,从历史上看,输入结束的Ctrl-Z必须位于行的开头.该行其他地方的Ctrl-Z效果不一样.

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.

这篇关于为什么在Windows控制台程序中按Ctrl + Z时有时仅终止输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆