我试图用C编写一个程序来打印通过getchar()输入的单词长度。这是代码:
#include<stdio.h>
#define IN 1
#define OUT 0
int main()
{
int c, chars, state, i;
int nlength[20];
state = OUT;
chars = 0;
for (i = 0; i < 20; ++i){
nlength[i] = 0;
}
while ((c = getchar()) != EOF){
if (c != ' ' && c != '\t' && c != '\n'){
state = IN;
++chars;
}
else if (state == OUT){
++nlength[chars];
chars = 0;
}
}
if (c == EOF){
++nlength[chars];
}
printf("\nLength of words = ");
for (i = 0; i < 20; ++i){
printf(" %d", nlength[i]);
}
printf("\n");
}
它应该输出,例如输入&#34; aaa aaa&#34;,:0 0 0 2 0 0 0 .... 但是,它会输出类似0 0 0 0 0 0 1 0 0 ...的内容。有谁能告诉我它有什么问题?
答案 0 :(得分:1)
在您的代码中state
永远不会更改为OUT
,因此以下行:
else if (state == OUT){
++nlength[chars];
chars = 0;
}
永远不会被执行。
还有一些地方看起来很可疑。例如。你永远不会检查阵列边界。此外,您不需要state
变量,只需检查chars > 0
。
以下是您的代码,但有一些修改:
#include <stdio.h>
// we can use isspace function from ctype.h
#include <ctype.h>
#define MAX_LEN 20
int main() {
int c;
int chars = 0;
// this way we don't have to zero the array explicitly
int nlength[MAX_LEN] = {0};
while ((c = getchar()) != EOF) {
if (!isspace(c))
++chars;
else {
// if chars == 0 we increment nlength[0]
// which is not used anyway
if (chars < MAX_LEN)
++nlength[chars];
chars = 0;
}
}
// if chars == 0 we increment nlength[0]
if (chars < MAX_LEN)
++nlength[chars];
// set 0-length words element to zero
nlength[0] = 0;
printf("\nLength of words = ");
for (int i = 0; i < MAX_LEN; ++i) {
printf(" %d", nlength[i]);
}
printf("\n");
}