为什么EOF(文件结束)没有在一行的末尾没有工作之前,它的'\\ n'? [英] Why EOF(end of file) isn't working at the end of a line without a '\n' before it?

查看:265
本文介绍了为什么EOF(文件结束)没有在一行的末尾没有工作之前,它的'\\ n'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我开始使用ANSI C书学习C。一书中的早期功能锻炼是写一个程序,需要文字输入和打印一个新行的每一个字,够简单。所以,我所做的:

So I started to learn C using the ANSI C book. One of the early exercises in the book is to write a program that takes text input and prints every word on a new line, simple enough. So i did:

#include <stdio.h>

#define IN 1
#define OUT 0

 main() { 

    int c;
    int state;

    state = OUT;

    while((c = getchar()) != EOF){
        if(c != ' ' && c != '\n' && c != '\t'){
            state = IN;
        }else if(state == IN){
            state = OUT;
            putchar('\n');
        }
        if(state == IN)
            putchar(c);
    }

     getchar();
 }

的事情是,当程序正常工作不会从while循环,如果我进入中断 EOF (按Ctrl + Z在Windows上)作为最后一个字符线或在它的中间。

The thing is that while the program works fine it won't break from the while loop if I enter EOF(Ctrl+Z on windows) as the last char of a line or in the middle of it.

于是我找到答案<一个href=\"http://stackoverflow.com/questions/11944314/ctrl-d-didnt-stop-the-whilegetchar-eof-loop\">here.

我了解到的是,(按Ctrl + Z)字符是某种信号的结束流,它必须对)的新线的getchar(来返回 EOF 。虽然这是所有好的,它有点帮助我真的想知道为什么是必要的 EOF 要在自己的行?

What I learned is that the (Ctrl+Z) char is some sort of signal to end the stream and it must be on a new line for getchar() to return EOF. While this is all good and it kinda helped I really want to know why is it necessary for the EOF to be on its own line?

推荐答案

您有涉及到你的命令行终端,并没有任何关系的文件标记本身​​的问题到底。而不是发送字符,当您输入的程序,大多数终端会等到你发送你键入程序之前完成一整行。

The problem you are having is related to your command line terminal and has nothing to do with the end of file marker itself. Instead of sending characters to the program as you type them, most terminals will wait until you finish a whole line before sending what you type to the program.

您可以通过具有输入来自一个文本文件,而不是用手正在键入测试。您应该能够结束不换行输入文件中没有任何问题。

You can test this by having the input come from a text file instead of being typed by hand. You should be able to end the input file without a newline without any problems.

./myprogram.exe < input.txt


顺便说一句,你链接的答案还指出,EOF不是人物,实际上是在你的输入流,所以没有办法为它之前一个\\ n来了。 EOF只是值的getchar 返回一旦没有剩余字符被读取。


By the way, the answer you linked to also points out that EOF is not a character that is actually in your input stream, so there is no way for it to come "before" a "\n". EOF is just the value that getchar returns once there are no characters left to be read.

这篇关于为什么EOF(文件结束)没有在一行的末尾没有工作之前,它的'\\ n'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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