计算C中用户输入字符串中的单词

所以,我们在课堂上得到了这个程序。 “用C编写程序来计算用户输入的句子中的单词数。” 这就是我能想到的,但是单词的数量总是比正确的数字少一个。 我的老师告诉大家,在打印之前只需在字数上加1。 我认为它有一个错误,如果我们不输入任何单词,即按Enter而不是键入,我老师建议的程序仍然会将单词计数为1而不是0.你知道有什么方法可以得到正确的单词算不算只加1? 码:

我的代码(给出1不正确):

#include  #include  void main() { char s[200]; int count = 0, i; printf("enter the string\n"); gets(s); for (i = 0;i<strlen(s);i++) { if (s[i] == ' ') count++; } printf("number of words in given string are: %d\n", count); } 

只是你在计算空间,如果用户用一堆空格结束字符串,这也是不正确的。 尝试这样的事情:

 #include  #include  void main() { char s[200]; int count = 0, i; int foundLetter = False; printf("enter the string\n"); gets(s); for (i = 0;i 

正如其他用户所评论的那样,根据输入的字符串,您的程序容易受到许多其他问题的影响。 我发布的例子假设任何不是空格的东西都是一个字母,如果你找到至少一个字母,那就是一个字。 您可以使用计数器来确保该单词至少具有一定的长度,而不是布尔值。 您也可以通过编写自己的正则表达式函数或使用现有函数来检查它是不是数字或符号。 正如其他人所说,你可以用这个程序做更多的事情,但我已经提供了一个例子来指出你正确的方向。

你正在计算非单词的数量,但你应该计算单词的数量。

如果一个单词被定义为一个或多个字母的序列,那么您的代码可能如下:

 for every character in the string if the character is part of a word ( "the car's wheel" is three words ) increase the word count while the character is part of a word, increment your pointer 

一个改进是处理在单词或制表符之间包含多个空格的行,同时仍然考虑简单地将'\n'作为单词返回。 使用getline提供了许多优点,包括提供读取的字符数。 以下是该方法的示例:

编辑逻辑简化:

 #include  int main (void) { char *line = NULL; /* pointer to use with getline () */ char *p = NULL; /* pointer to parse getline return */ ssize_t read = 0; size_t n = 0; int spaces = 0; /* counter for spaces and newlines */ int total = 0; /* counter for total words read */ printf ("\nEnter a line of text (or ctrl+d to quit)\n\n"); while (printf (" input: ") && (read = getline (&line, &n, stdin)) != -1) { spaces = 0; p = line; if (read > 1) { /* read = 1 covers '\n' case (blank line with [enter]) */ while (*p) { /* for each character in line */ if (*p == '\t' || *p == ' ') { /* if space, */ while (*p == '\t' || *p == ' ') /* read all spaces */ p++; spaces += 1; /* consider sequence of spaces 1 */ } else p++; /* if not space, increment pointer */ } } total += spaces + 1; /* words in line = spaces + 1 */ printf (" chars read: %2zd, spaces: %2d total: %3d line: %s\n", read, spaces, total, (read > 1) ? line : "[enter]\n"); } printf ("\n\n Total words read: %d\n\n", total); return 0; } 

输出:

 Enter a line of text (or ctrl+d to quit) input: my chars read: 3, spaces: 0 total: 1 line: my input: dog has chars read: 8, spaces: 1 total: 3 line: dog has input: fleas and ticks chars read: 17, spaces: 2 total: 6 line: fleas and ticks input: chars read: 1, spaces: 0 total: 7 line: [enter] input: chars read: 1, spaces: 0 total: 8 line: [enter] input: total_words 10 chars read: 17, spaces: 1 total: 10 line: total_words 10 input: Total words read: 10 
 //input should be alphanumeric sentences only #include  using namespace std; int main() { freopen("count_words_input.txt","r",stdin); // input file char c; long long i,wcount=0,f=0; i=0; while(scanf("%c",&c) == 1) { if(c == ' ' || c == '\n' || c == '\t' || c == '.') f=0; else if(f == 0) { wcount++; f=1; } } printf("%lld\n",wcount); return 0; }