2

So, we were given this program in class. "Write a Program in C to count the number of words in a sentence input by the user." This is what i could come up with, but the number of words is always one less than what is the correct number. My teacher told everyone to just add 1 to the word count before printing it. I think it has a bug, if we don't enter any words, i.e. , press Enter instead of typing,the program suggested by my teacher would still give word count as 1 not 0. Do you know of any way to get proper word count without just adding 1 at the end? Code:

My code(giving 1 less than correct) :

#include <stdio.h>
#include <string.h>
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);
}
5
  • 3
    What if the user enters two spaces next to each other? one two Commented Sep 9, 2014 at 13:50
  • 1
    Please compile with all warnings and debug info (gcc -Wall -g). Also, don't use gets but fgets. At last learn right now how to use the debugger Commented Sep 9, 2014 at 13:50
  • don't use gets(), but fgets, you may also use \n as a word delimiter. Commented Sep 9, 2014 at 13:50
  • Read about isalpha(3) etc etc... Think about Hello, I am ... John-F Kennedy! as an input. Commented Sep 9, 2014 at 13:52
  • @BasileStarynkevitch: Sure, but it is a good idea for him to try it himself. The problem is full of quirks that will teach him lots of stuff. Using a function is not a good idea. Commented Sep 9, 2014 at 13:53

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! This is exactly what I was trying to figure out :)
main should be int and not void. What exactly is False and True?
1

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 

1 Comment

+1 You hit the nail on the head: "You are counting the amount of non-words"
0

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

2 Comments

regarding this line: if (*p != '\t' || *p != ' ') { *p cannot be both conditions, so this line will always evaluate to true
Good catch, should be &&
0
//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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.