Search code examples
csplitc-stringsfunction-definition

What is the data type of text[i]?


I'm trying to count the number of words in a string entered by the user with this custom function:

int count_words(char* text)
{
   int wc = 0;
   for(int i = 0,k = strlen(text); i<k;i++)
   {
      if(strcmp(" ",text[i]) ==0 || strcmp(".",text[i]) ==0 || strcmp("!",text[i]) ==0 || strcmp("?",text[i]) ==0 || strcmp(",",text[i]) ==0)
      {
          wc++;
      }
   }
    return wc+1;
}

but I keep getting this error:

re.c:59:21: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
      if(strcmp(" ",text[i]) ==0 || strcmp(".",text[i]) ==0 || strcmp("!",text[i]) ==0 || strcmp("?",text[i]) ==0 || strcmp(",",text[i]) ==0)
                    ^~~~~~~
                    &

re.c:59:48: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
      if(strcmp(" ",text[i]) ==0 || strcmp(".",text[i]) ==0 || strcmp("!",text[i]) ==0 || strcmp("?",text[i]) ==0 || strcmp(",",text[i]) ==0)
                                               ^~~~~~~
                                               &

What is really happening?


Solution

  • strcmp takes char * (string) not a single char. It's better if you use strtok` to count the number of words in a string.

    Here's a simple example

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
    
      char arr[] = "Temp hello bye! No way. Yes";
      char *delimeters = " !.";
    
      char *token = strtok(arr, delimeters);
      int count = 0;
    
      while (token != NULL) {
        count++;
        token = strtok(NULL, delimeters);
      }
      printf("Words = %d", count);
    
      return 0;
    }
    

    You can use strpbrk instead of strtok as well.