C - Saving values ​​from text to arrays

I am trying to save various values ​​that are taken from a file line by line. Lines in a text file read like something below

100000,player1,long title name 300000,someotherplayer,another long title name 45512845,thisplayer,one more long title name 

I want to save each value separated by a comma into three different arrays, (int) number, (str) player_name, (str) title_name.

I have the code below, but it does not compile.

 ptr_file=fopen("text.txt", "r"); char buffer[1000]; int line; line = 0; while(fgets(buffer, sizeof(buffer), ptr_file) != NULL){ char number[line]=strtok(buffer, ","); char player_name[line]=strtok(NULL, ","); char title_name[line]=strtrok(NULL, ","); } 

Can someone give me some advice on this?

+4
source share
3 answers

So there are a few problems with your code,

You open the file in "o" mode, which I'm not quite sure what it is, I suspect you want the "r" strtok returns a char *, which you cannot assign to char []. One second pass through the loop, you will overwrite the data in the buffer. I would do something like this:

 struct player { int number; char player_name[64]; char title_name[256]; }; int main(void) { FILE *ptrfile=fopen("text.txt", "r"); char buffer[1000]; int line; struct player players[16]; line = 0; if(ptrfile==NULL) return 0; while(fgets(buffer, sizeof(buffer), ptrfile) != NULL){ if(strcmp(buffer, "") == 0) return 0; char *number=strtok(buffer, ","); char *player_name=strtok(NULL, ","); char *title_name=strtok(NULL, ","); players[line].number=atoi(number); strcpy(players[line].player_name, player_name); strcpy(players[line].title_name, title_name);; line++; } fclose(ptrfile); return 0 } 
+2
source

The strtok function returns a pointer, so it must be

 char* p = strtok(...) 

Check link here

+1
source

This is what I did, it was like what you seem to be doing. The problem that you find is that you want to make each value in char *, but you must malloc each, then you can connect this char * to an array. It would also be easier to do this with numbers, then to include them in an int later.

 #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char *msg[100]; char temp[100]; int length, i; int num = 0; while((scanf("%s", &temp[0]) != EOF)) { length = strlen(temp); msg[num] = malloc((length+1 )* sizeof(char)); strcpy(msg[num], temp); num++; } printf("There are %d words in the this input.\n", num); for(i = 0; i < num; i++) { printf("%s\n", msg[i]); } return 0; } 

The thing with malloc is that you have to have each one unique, because the words have different sizes. I know that this example is not exactly what you are doing, but it will help you in the right direction.

+1
source

Source: https://habr.com/ru/post/1447859/


All Articles