C编程:EOF作为字符 [英] C Programming: EOF as a character

查看:203
本文介绍了C编程:EOF作为字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当为命令控制台编写C时,如果有一个函数试图使用SCANF向用户输入CHAR变量,并且用户输入 CTRL + Z (EOF)and hits enter?

When programming C for the command console, what happens when you have a function that tries to use SCANF to ask user input for a CHAR variable, and the user types CTRL+Z (EOF) and hits enter?

例如:

char promptChar()
{
    char c;
    printf("Enter a character: ");
    scanf("%c", &c);
    return c;
}

如果用户键入 CTRL + Z 并点击Enter,promptChar()会返回什么?因为如果我理解EOF,它就是一个整数。

If the user types CTRL+Z and hits enter, what will promptChar() return? Because if I understand EOF, it's an int.

推荐答案

第一件事:

SCANF 未由语言定义。

CHAR 未定义语言。

SCANF is not defined by the language.
CHAR is not defined by the language.

好吧,好吧,

scanf )函数返回一个整数。如果在第一次转换之前发生输入失败,那么该整数是分配的输入项数量或者 EOF 的值。

您没有检查 scanf()调用的返回值,因此您不知道发生了什么。一切都可能工作正常,或者输入流可能在第一次转换之前已经结束,或者(不是%c)可能已经发生转换失败。

The scanf() function returns an integer. That integer is the number of input items assigned or the value of the macro EOF if an input failure occurs before the first conversion.
You didn't check the return value of the scanf() call, so you have no idea what happened. Everything might have worked ok, or the input stream might have ended before the first conversion, or (not for %c) there might have been a conversion failure.

测试返回值 scanf()。实际上,总是测试所有< stdio.h>的返回值。函数

Test the return value of scanf(). Indeed, always test the return value of all <stdio.h> functions.

char ch;
int result = scanf("%c", &ch);
if (result == 1) /* all ok */;
else if (result == 0) /* conversion failure: value of `ch` is indeterminate */;
else if (result == EOF) /* input failure; value of `ch` is indeterminate */;

scanf()调用 EOF ,如果您想了解更多关于输入失败原因的信息,可以使用 feof() ferror()

When the result of the scanf() call is EOF, if you want more information about the reason for input failure, you can use feof() and/or ferror().

else if (result == EOF) {
    if (feof(stdin)) {
        /* no data in input stream */
    }
    if (ferror(stdin)) {
        /* error if input stream (media ejected? bad sector? ...?)
    }
}


$ b b




要回答你的问题: promptChar()会返回什么?

它将返回char类型的不确定值。

你可以按照处理字符的库函数的示例,并从 promptChar()返回一个int 。这将是在错误的情况下字符读取转换为 unsigned char 或负整数( EOF )的值。阅读 fgetc()

It will return an indeterminate value of type char.
You could follow the example of library function that deal with characters and return an int from promptChar(). That would be the value of the character read cast to unsigned char or a negative int (EOF) in case of error. Read the description for fgetc(), for instance.

这篇关于C编程:EOF作为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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