【问题标题】:Trying to count the number of commas in a string and save to a int counter尝试计算字符串中逗号的数量并保存到 int 计数器
【发布时间】:2020-05-04 14:56:11
【问题描述】:

我不断收到一条错误消息,上面写着“警告:指针和整数之间的比较”。我已经尝试使用 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] == ",") 中,您尝试将字符与字符串文字进行比较,请改用count += (buff[i] == ',')
  • 为什么for(i=0;i&lt;buff[i] != 0; i++){ 中有i&lt;
  • 抱歉打错了

标签: c loops counter c-strings


【解决方案1】:

例如在这个语句中

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

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

您需要将字符与使用字符文字',' like 的字符进行比较

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];

【讨论】:

    猜你喜欢
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    相关资源
    最近更新 更多