I got a error. "Passing argument 1 'strchr' makes pointer from integer without a cast"
How can I fix that ?
this happen in const char *ptr = strchr(c, ';');
and I'm trying to do is just get the index of a specific char in a char array.
In my File, I have for example 100 lines, and in each line, i has something like that 12345;Lucas , so I need to split this, numbers and letters and I'm trying to search the " ; " and separate.
Follow my code
FILE *fp;
char c;
char c2[100];
int i = 0;
fp = fopen("MyFile.csv", "r");
if (!fp) {
printf("Error!\n");
exit(0);
}
while((c = getc(fp)) != EOF){
for (i = 0; i < 1; i++)
{
const char *ptr = strchr(c, ';');
if(ptr) {
int index = ptr - c;
printf("%d", index);
}
}
printf("%c", c);
}
您的变量c
是单个字符,而不是char数组。
There is no need to implement this on the basis of getc
and strchr
.
if your data is organized in lines, then you should use fgets
to read the file line-wise. if your data is separated by ';'
, then you should use sscanf
to split the line buffer into substrings.
See this post for an example program that solves a similar problem.
strchr
is used to search for a specific character within a NULL terminated string. To compare two characters simply use ==
if( c == ';' ) {
// do something
}
this is crazy code! No idea what the for loop is.... maybe you want something like...
while(fgets(c2, 100, fp) != NULL)
{
char* first = c2;
char *second = c2;
// look for a ; or the end of the string...
while(*second != ';' && *second != 0) second++;
if(*second == 0) continue; // if there was no ; just carry on to the next line
*second = 0; second++; // put a terminator where the ; was
// first will now point to the first string :- 123456
// second will now point to the second part :- Lucas
printf("%s %s\r\n", first, second);
// you may want to trim the second part of \r\n chars.
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp;
char c;
char c2[100];
int i = 0;
fp = fopen("MyFile.csv", "r");
if (!fp) {
printf("Error!\n");
exit(-1);
}
while(NULL!=fgets(c2,100,fp)){//fgets read one line or 100 - 1 char
char *ptr = strchr(c2, ';');
if(ptr) {
int index = ptr - c2;
printf("index of %c is %d\n", *ptr, index);
*ptr = '\0';
//12345;Lucas -> first is "12345", second is "Lucas"
printf("split string first is \"%s\", second is \"%s\"\n", c2, ptr + 1);
}
}
fclose(fp);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.