Search code examples
cloopscharcounterc-strings

Trying to count the number of commas in a string and save to a int counter


I keep getting an error that says "warning: comparison between pointer and integer". I have tried using char* and still got the same error. I want to count the number of commas that appear in a string and place the number of occurrences into a counter.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


int main(int argc, char *argv[]) {

    /*FILE *fp;
    fp = fopen("csvTest.csv","r");
    if(!fp){
        printf("File did not open");
    }*/


    //char buff[BUFFER_SIZE];
    char buff[100] = "1000,cap_sys_admin,cap_net_raw,cap_setpcap";    

    /*fgets(buff, 100, fp);
    printf("The string length is: %lu\n", strlen(buff));
    int sl = strlen(buff);*/

    int count = 0;
    int i;
    for(i=0;buff[i] != 0; i++){
        count += (buff[i] == ",");
    }
    printf("The number of commas: %d\n", count);




    char *tokptr = strtok(buff,",");
    char *csvArray[sl];

    i = 0;
    while(tokptr != NULL){
          csvArray[i++] = tokptr;
          tokptr = strtok(NULL, ",");
    }

    int j;
    for(j=0; j < i; j++){
        printf("%s\n", csvArray[j]);
    }

    return 0;
}

Solution

  • For example in this statement

    count += (buff[i] == ",");
    

    you are comparing the object buff[i] that has the type char with the string literal "," that in the expression of comparison is implicitly converted to the type const char *.

    You need to compare a character with a character using the character literal ',' like

    count += (buff[i] == ',');
    

    Another approach is to use the standard C function strchr.

    for ( const char *p = buff; ( p = strchr( p, ',' ) ) != NULL; ++p )
    {
        ++count;
    }
    

    Pay attention to that there is a typo in the condition of the loop

    for(i=0;i<buff[i] != 0; i++){
    

    You have to write

    for(i=0; buff[i] != 0; i++){
    

    Also it seems that instead of this declaration

    char *csvArray[sl];
    

    you mean something like

    char *csvArray[count + 1];