如果用户输入多行/空格,如何计算单词数?

时间:2018-05-09 12:27:20

标签: c arrays if-statement while-loop

我有一个char数组,其中包含用户输入的内容。我怎么算数字呢? 允许用户做某事疯狂的用户:

hello this
               is a test
   how are
you today?

所以这里的单词数量应为9,但我的程序告诉我23.为什么这不起作用?它计算空间,但我考虑到了sentence_entered[i + 1] != ' '

我的代码:

int i = 0;    
while (sentence_entered[i] != '\0') {

        if (
            (sentence_entered[i] == ' ' ||
            sentence_entered[i] == '\n') &&
            (sentence_entered[i + 1] != ' ' ||
            sentence_entered[i + 1] != '\n')
           ) {
            words += 1;
    }
i++
}

1 个答案:

答案 0 :(得分:5)

a || b的否定是!a && !b

您的情况应为:

       (sentence_entered[i] == ' ' ||
        sentence_entered[i] == '\n') &&
        (sentence_entered[i + 1] != ' ' &&
        sentence_entered[i + 1] != '\n')