As the code is currently, it outputs:
hjk
hg
kjgj
Word 0: 12
Word 1: 0
Word 2: 0
When it should be:开发者_开发知识库
Word 0: 3
Word 1: 2
Word 2: 4
I don't know what I am doing wrong, here is the code:
#include <stdio.h>
#define MAX_WORDS_COUNT 10
main()
{
int wordsLength[MAX_WORDS_COUNT];
int i, c, inspace = 0, currWord = 0;
for (i = 0; i < MAX_WORDS_COUNT; i++)
wordsLength[i] = 0;
while ((c = getchar()) != EOF) {
if (c != ' ' || c != '\t' || c != '\n') {
wordsLength[currWord]++;
inspace = 0;
} else {
if (inspace == 0)
currWord++;
inspace = 1;
}
}
for(i = 0; i < MAX_WORDS_COUNT; i++)
printf("Word %d: %d\n", i, wordsLength[i]);
}
if (c != ' ' || c != '\t' || c != '\n') {
You should be using &&. You've got 3 mutually exclusive conditions, and are ORing them, which means ALL conditions satisfy this.
if (c != ' ' && c != '\t' && c != '\n') {
will work.
You want &&
instead of ||
in your condition...otherwise look at the output you posted, it thinks all 12 characters belong to one word.
Change this: if (c != ' ' || c != '\t' || c != '\n')
To: if (c != ' ' && c != '\t' && c != '\n')
精彩评论