首页 > 解决方案 > 如何找出用户输入在 C 中的时间长度?

问题描述

#include <stdlib.h>
int main(){
int sum=1;
char sent[50];
fgets(sent, sizeof(sent), stdin);
for(int i=0;i<=strlen(sent);i++){
    if(i==' '){
        sum++;
    }
}
scanf("%s", sum);


return 0;
}

我想要的是找出句子中有多少个单词。我怎样才能知道句子有多长?提前致谢。

标签: c

解决方案


继续@chux 的伪代码,实现将是:

#include <stdio.h>
#include <ctype.h>

#define MAXS 50         /* if you need a constant, #define one (or more) */

int main (void){

    int sum = 0, i = 0, inword = 0;     /* use inword as a flag, in/out word */
    char sent[MAXS];
    
    if (fgets(sent, sizeof(sent), stdin) == NULL) { /* read/VALIDATE input */
        fputs ("(user canceled input)\n", stderr);
        return 1;
    }
    
    while (sent[i]) {                   /* loop over each character */
        if (isspace(sent[i])) {         /* is the character a space? */
            inword = 0;                 /* set flag to false */
        }
        else {  /* otherwise */
            if (!inword)                /* if we were reading spaces, now in word */
                sum += 1;               /* increment sum */
            inword = 1;                 /* set flag true */
        }
        i++;                            /* increment loop counter */
    }
    
    printf ("whitespace separated words: %d\n", sum);
}

您保留一个“状态”变量inword,该变量跟踪您是否“在一个单词中”读取字符,或者在读取空格的单词之前、之间或之后的状态。这也确保忽略前导空格、多重包含空格和尾随空格。


推荐阅读