gpt4 book ai didi

c - K&R 练习 6-1 某些情况下 getword 函数无法读取 EOF

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:44 25 4
gpt4 key购买 nike

我刚刚完成The C Programming Language一书的练习 6.1,第二版(作者:The C Programming Language>K&R),这是练习题:

Our version of getword does not properly handle underscores, string constants, comments, or preprocessor control lines. Write a better version.

这里是书中的getword函数:


int getword(char *word, int lim)
{
int c;
char *w = word;
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
if (!isalpha(c)) {
*w = '\0';
return c;
}
for ( ; --lim > 0; w++)
if (!isalnum(*w = getch())) {
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}

在 main() 中调用函数:


while (getword(word, MAXWORD) != EOF) {...}

这是我的 getword 函数:

int getword(char *word, int lim)
{
int c, c1;
char *w = word;
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
else
return EOF;
// handle comments: /* */
if ( c == '/') {
if ((c1 = getch()) == '*') {
keytab[31].count++;
int ok = 1;
while (ok) {
// skip characters in comment lines
while ((c = getch()) != EOF || c != '*')
;
if (c == EOF)
return EOF;
if ((c = getch()) == '/')
ok = 0;
}
return COMMENT;
}
// handle comments : //
else if (c1 == '/') {
keytab[32].count++;
while ((c = getch()) != EOF || c != '\n')
;
if (c == EOF)
return EOF;
return COMMENT;
}
else
return c;
}
// handle preprocessor control lines, start with '#'
if (c == '#') {
keytab[34].count++;
while ((c = getch()) != EOF || c != '\n')
;
if (c == EOF)
return EOF;
return '#';
}
// handle string constants, " "
else if (c == '\"') {
while ((c1 = getch()) != EOF || c1 != '\"')
;
if (c1 == EOF)
return EOF;
keytab[33].count++;
return CONSTANT;
}
else if (c != '_' && !isalpha(c)) {
while ((c = getch()) != EOF && !isspace(c))
;
if (c == EOF)
return EOF;
return NOT;
}
// c is '_' or letter , scan characters until EOF or space, or punctuation
// to get a complete word
for ( ; --lim > 0; w++)
if ((*w = getch()) == EOF || isspace(*w) || ispunct(*w)) {
ungetch(*w);
break;
}
*w = '\0';
return WORD;
}

如果我不输入"///*#,代码将运行正常,可以通过enterint ctrl + d 停止输入,但是一旦输入上述任一字符,程序就读不到EOF,无法停止输入,用gdb调试程序,还是不行不明白。那么会发生什么?

最佳答案

&&||

while ((c = getch()) != EOF || c != '*')

以上总是正确的。

也许

while ((c = getch()) != EOF && c != '*')

关于c - K&R 练习 6-1 某些情况下 getword 函数无法读取 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58767516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com