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

ldd*_*345 2 c counter loops c-strings char

我不断收到一条错误消息“警告:指针和整数之间的比较”。我尝试使用 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;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

例如在这个声明中

count += (buff[i] == ",");
Run Code Online (Sandbox Code Playgroud)

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

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

count += (buff[i] == ',');
Run Code Online (Sandbox Code Playgroud)

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

for ( const char *p = buff; ( p = strchr( p, ',' ) ) != NULL; ++p )
{
    ++count;
}
Run Code Online (Sandbox Code Playgroud)

注意循环的条件有错字

for(i=0;i<buff[i] != 0; i++){
Run Code Online (Sandbox Code Playgroud)

你必须写

for(i=0; buff[i] != 0; i++){
Run Code Online (Sandbox Code Playgroud)

而且似乎不是这个声明

char *csvArray[sl];
Run Code Online (Sandbox Code Playgroud)

你的意思是

char *csvArray[count + 1];
Run Code Online (Sandbox Code Playgroud)