Count words in a user-input string in C

和自甴很熟 提交于 2019-12-06 04:35:40

It's just that you're counting spaces, this would also be incorrect if the user ended the string with a bunch of spaces. Try something like this:

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

As other users have commented, your program is susceptible to many other issues depending on the string inputed. The example I have posted assumes that anything that is not a space is a letter and if you find at least one letter, than that's a word. Instead of boolean values you could use a counter to make sure that the word is at least a certain length. You could also check to see that it is not a number or symbol by either writing your own regex function or using an existing one. As others have said there is a lot more you can do with this program, but I've provided an example to point you in the right direction.

You are counting the amount of non-words, but you should be counting the amount of words.

If a word is defined as a sequence of one or more letters, your code might go as:

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 

One improvement would be to handle lines that contain multiple spaces between words or tabs, while still considering a simple return '\n' as a word. Using getline provides a number of advantages including providing the number of characters read. Here is an example of the approach:

Edit logic simplified:

#include <stdio.h>

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;

}

output:

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 <bits/stdc++.h>
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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!