所以我正在学习C编程语言这本书。解决计算器的问题。它要求添加对负数的支持;我这样做了,但我发现了一种奇怪的行为,我无法解释。
int getop(char s[])
{
int i = 0, c, next;
/* Skip whitespace */
while((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
/* Not a number but may contain a unary minus. */
if(!isdigit(c) && c != '.' && c != '-')
return c;
if(c == '-')
{
next = getch();
if(!isdigit(next) && next != '.')
return c;
c = next;
}
else
c = getch();
while(isdigit(s[++i] = c)) //HERE
c = getch();
if(c == '.') /* Collect fraction part. */
while(isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if(c != EOF)
ungetch(c);
return NUMBER;
}适用于正数和负数
int getop(char s[])
{
...
while(isdigit(s[++i] = c = getch())) //HERE
;
if(c == '.') /* Collect fraction part. */
while(isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if(c != EOF)
ungetch(c);
return NUMBER;
}仅适用于正数。
为什么!?
getch()
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getch(void) /* get a (possibly pushed-back) character */ {
return (bufp > 0) ? buf[--bufp] : getchar();
}谢谢。
发布于 2011-03-30 06:24:51
while(isdigit(s[++i] = c))
c = getch();和
while(isdigit(s[++i] = c = getch()))
;有不同的行为。后者在进入循环之前读取一次,并检查读取的值是否为数字,而前者检查先前读取的值是否为数字。
https://stackoverflow.com/questions/5479630
复制相似问题