我不断收到一条错误消息,提示“警告:指针和整数之间的比较”。我尝试使用 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 *
。
您需要使用字 rune 字 ','
来比较一个字符与一个字符
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];
关于c - 尝试计算字符串中逗号的数量并保存到 int 计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61595191/