尝试计算字符串中逗号的数量并保存到 int 计数器

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

我不断收到一条错误消息 "warning: comparison between pointer and integer"。我试过使用 char*,但仍然遇到同样的错误。我想计算出现在字符串中的逗号的数量,并将出现的次数放入计数器中。

#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;
}

比如在这个语句中

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

您正在将类型为 char 的对象 buff[i] 与在比较表达式中隐式转换为类型 const char * 的字符串文字 "," 进行比较.

您需要使用字符文字 ',' 来比较一个字符与一个字符

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

另一种方法是使用标准 C 函数 strchr

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

注意循环条件有错别字

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

你必须写

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

而且似乎不是这个声明

char *csvArray[sl];

你的意思是

char *csvArray[count + 1];