我正在学习 C 编程语言。
在下面的代码中
#include <ctype.h>
int getch(void);
void ungetch(int);
int getop(char s[])
{
int i, c;
while((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if(!isdigit(c) && c != '.')
return c;
i = 0;
if (isdigit(c))
while (isdigit(s[++i] = c = getch())) ;
if(c == '.')
while (isdigit(s[++i] = c = getch())) ;
s[i] = '\0';
if(c != EOF)
ungetch(c);
return NUMBER;
}
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
我认为getop()
中的语句if(c != EOF)
是不必要的。
在标准输入中,每行由零个或多个字符组成,后跟一个换行符。
当语句执行时,c取到的内容后面是一个数字字符或.
,这种情况下c可以是换行符或除EOF
之外的其他字符。
未经测试,很明显 c
不是 EOF
。
if(c != EOF)
的用途是什么?
抱歉,如果这是一个微不足道的问题。 提前致谢。
最佳答案
In standard input, each line consists of zero or more characters followed by a newline character.
不一定;输入是任意字节流,不必以换行符结尾。
When the statement executes,what c has fetched follows a digit character or a .,in which situation c could be a newline character or other characters except for EOF.
也可能是 EOF。
It is clear that c is not EOF without testing.
不,不是;事实上,很明显 c 可能是 EOF。
What is if(c != EOF) used for?
防止 ungetch(EOF),这是未定义的,因为 EOF 不能塞进 buf 中。
附注如果程序确实读取了 EOF,或者输入流包含 char 范围正数部分之外的值,则程序具有未定义的行为... isdigit 的参数应始终是 int,但这里是 char。
关于c - if (c != EOF) 用于逆波兰计算器中的内容是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18268630/