简体   繁体   English

C ++使用cin.get获取字符,但遇到EOF时不结束while循环

[英]C++ use cin.get to get a character, but not end the while loop when encounter the EOF

The following is my code, that I want to read characters from stdin, and end when it meet an EOF(ctrl-z). 以下是我的代码,我想从stdin中读取字符,并在遇到EOF(ctrl-z)时结束。

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
using namespace std;

int main()
{
    string article ;    
    char nextChar;
    while( cin.get(nextChar) ) {
        if( cin.eof() ) break ;
        article.append(1, nextChar) ;
    }

    cout << article ;

    system("pause") ;
}

I test an input like this: 我测试这样的输入:

I am a student.<ctrl-z>

And then I press enter, but it does not halt. 然后按Enter键,但它没有停止。

When I type another [ctrl-z], and then press neter. 当我键入另一个[ctrl-z]时,然后按neter。

It just can exit from the while loop. 它只是可以从while循环中退出。

Why the first [ctrl-z] not to signal the eof condition? 为什么第一个[ctrl-z]不通知eof条件?

The following explanation is slightly simplified. 以下说明略有简化。

It's a feature of your operating system. 这是您的操作系统的功能。 This is how your operating system works. 这就是您的操作系统的工作方式。

An end of file is, really, the underlying read() system call returning 0. An end of file is not CTRL-Z . 实际上,文件结尾是底层的read()系统调用,返回0。文件结尾不是CTRL-Z CTRL-Z gets interpreted by your operating system to flush its interactive key buffer, and have the process read() its contents. 操作系统将CTRL-Z解释为刷新其交互式键缓冲区,并使进程read()其内容。

When you type in a terminal, the process does not actually end up reading anything until Enter is pressed. 当您输入终端时,该过程实际上直到Enter才结束读取任何内容。 At that time the read() system call completes, and returns everything that's been read. 到那时, read()系统调用完成,并返回已读取的所有内容。 In general, before pressing Enter you can backspace and edit what you typed, and your program has no indication that you've edited anything, all that it read ()s is the final contents of the line after pressing Enter . 通常,在按Enter键之前,您可以退格并编辑您键入的内容,并且程序不表示您已编辑了任何内容,它所read全部内容是按Enter后该行的最终内容。

If you type something, and press CTRL-Z , the typed input is also read () by the program as if it was typed in. 如果键入内容,然后按CTRL-Z ,则键入的输入也read被程序read (),就像键入一样。

Only if nothing is typed, and CTRL-Z is pressed, does the underlying read() system call returns 0, because nothing got typed in first; 仅当未键入任何内容并按下CTRL-Z ,底层的read()系统调用才会返回0,因为首先没有键入任何内容。 this is interpreted as an end-of-file indication. 这被解释为文件结束指示。 But if something gets typed in first, CTRL-Z needs to be entered twice, once to read() the typed in input, and clear the input buffer, then CTRL-Z a second time, to cause an read () of 0. 但是,如果首先输入某些内容,则需要输入两次CTRL-Z ,一次read()输入的输入,然后清除输入缓冲区,然后再次CTRL-Z ,导致read ()为0。

By the way, your code has a harmless bug. 顺便说一句,您的代码有一个无害的错误。 If cin.get() succeeds, cin.eof() can never be true. 如果cin.get()成功,则cin.eof()永远不会为真。

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

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