EOF宏如何与getchar一起使用? [英] How does the EOF macro work with getchar?

查看:117
本文介绍了EOF宏如何与getchar一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

int main(void) {
    FILE *fp;
    int ch;
    fp = fopen("input.txt", "w");
    printf("Enter data");
    while ((ch = getchar()) != EOF) {
        putc(ch, fp);
    }
    fclose(fp);
    fp = fopen("input.txt", "w");
    while ((ch = getc(fp)) != EOF) {
        printf("%c", ch);
    }
    fclose(fp);
}

第一个期间循环停止从用户输入?
因为存在 EOF 作为条件。

How does the first while loop stop inputting from user? Since there is EOF present as a condition.

否则我是否需要使用进行循环?

Or else do I need to use for loop?

推荐答案

EOF 是一个值,而不是一个函数。

EOF is a value, not a function. It is essentially defined as a macro.

作为参考,摘自 C11 ,第7.21.1章,< stdio.h>

For reference, from C11, chapter §7.21.1, <stdio.h>


EOF

扩展为一个整数常量表达式,类型为 int 并为负值,表示
由多个函数返回指示文件结束,即不再有
流的输入; [...]

EOF
which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;[...]

情况下, getchar() 失败,它将返回定义为 EOF 的值。

从手册页引用(重点矿


fgetc() getc() getchar()将以无符号字符形式读取的字符转换为文件末尾的int或 EOF

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

EOF 表示值th可能不适合 char 类型。您必须对 ch 变量使用 int 类型。

EOF represents a value that may not fit into a char type. You must use int type for ch variable.


第一个while循环如何停止从用户输入?

use <在Linux上为kbd> CTRL + D ,在Windows上为 CTRL + Z

use CTRL+D on linux, and CTRL+Z on windows.

这篇关于EOF宏如何与getchar一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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