我是一名初出茅庐的 C 程序员,我编写了这个程序来计算第 2 版 K&R 1.5.4 的字数。我的 if 语句有问题吗?该代码似乎在不应该增加变量时增加了变量,因为它不符合初始测试。
#include <stdio.h>
#define IN 1
#define OUT 0
main()
{
int word, state, c;
word = state = OUT;
while((c = getchar()) != EOF)
{
if(c != ' ' || c != '\n' || c != '\t')
{
if(state == OUT)
{
word++;
state = IN;
}
/*else
{
state = IN;
}*/
}
if(c == ' ' || c == '\n' || c == '\t')
{
state = OUT;
}
printf("char: %c %x | state: %d | word: %d\n", c, c, state, word);
}
printf("\n//maniac: %d\n", word);
这导致:
>count_word_my.exe
Hello he he
char: H 48 | state: 1 | word: 1
char: e 65 | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: o 6f | state: 1 | word: 1
char: 20 | state: 0 | word: 1
char: 20 | state: 0 | word: 2
char: h 68 | state: 1 | word: 3
char: e 65 | state: 1 | word: 3
char: 20 | state: 0 | word: 3
char: 20 | state: 0 | word: 4
char: 20 | state: 0 | word: 5
char: h 68 | state: 1 | word: 6
char: e 65 | state: 1 | word: 6
char:
a | state: 0 | word: 6
char:
a | state: 0 | word: 7
//maniac: 7
我修改的K&R代码:
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
printf("char: %c %x | state: %d | word: %d\n", c, c, state, nw);
}
printf("%d %d %d\n", nl, nw, nc);
}
K&R 代码导致:
>count_word_test.exe
Hello he he
char: H 48 | state: 1 | word: 1
char: e 65 | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: o 6f | state: 1 | word: 1
char: 20 | state: 0 | word: 1
char: 20 | state: 0 | word: 1
char: h 68 | state: 1 | word: 2
char: e 65 | state: 1 | word: 2
char: 20 | state: 0 | word: 2
char: 20 | state: 0 | word: 2
char: 20 | state: 0 | word: 2
char: h 68 | state: 1 | word: 3
char: e 65 | state: 1 | word: 3
char:
a | state: 0 | word: 3
char:
a | state: 0 | word: 3
2 3 16
^C
当我的代码不满足第一个 if 语句中的测试时,它如何在处理“Hello”之后的第二个空格 (0x20) 时增加 word/nw?即使它确实到达了第二个 if 语句,我也会假设它将“状态”变量设置为 1(IN)。我在这里遗漏了一些重要的东西。我非常感谢提供的任何帮助。谢谢你。