首页 > 代码库 > 第一章 简介

第一章 简介

1.1getwordincrements linenumin scan forward to a nonspace or

EOF6but not after copy the word into buf[0..size-1]7when a

word endsat a new-line character. Explain why. What would happen if linenumwere incremented in this case?

在<scan forward to a nonspace or EOF 6>中将linenum加1,是因为‘\n‘也属于空白字符。
如果linenum在<copy the word into buf[0..size-1] 7>之后linenum加1这样对‘\n‘的统计就不准确了,例如有连续空行的时候。

1.2 What does doubleprint when it sees three or more identical

words in its input? Change doubleto fix this “feature.”


当出现连续3个或者3个以上的相同单词时,假如n个,则将会打印n-1个。
fix:
=====
if (isalpha(word[0]) && strcmp(prev, word)==0)
    <wordis a duplicate 8>
strcpy(prev, word);
=====
if (isalpha(word[0]) && strcmp(prev, word)==0) {
    <wordis a duplicate 8>
    world[0] = ‘\0‘;
}
strcpy(prev, word);

1.3 Many experienced C programmers would include an explicit comparison in strcpy’s loop:

char *strcpy(char *dst, const char *src) {

char *s = dst;

while ((*dst++ = *src++) != ‘\0‘)

    ;

    return s;

}

The explicit comparison makes it clear that the assignment isn’t a

typographical error. Some C compilers and related tools, like

Gimpel Software’s PC-Lint and LCLint (Evans 1996), issue a warning when the result of an assignment is used as a conditional,

because such usage is a common source of errors. If you have PCLint or LCLint, experiment with it on some “tested” programs.


编程风格问题,对于一些条件语句加些显示的判断会使程序看上去清晰很多。

第一章 简介