Getting words from text file to an array

前端 未结 3 1796
既然无缘
既然无缘 2021-01-14 12:43

My text file is formated like that:

my.txt
Red
Green
Blue
Yellow

I\'m tring to get words like that:

typedef char * string;
         


        
3条回答
  •  一生所求
    2021-01-14 13:07

    Since all the other answers told you what you did wrong but not how to fix it. Here

    typedef char * string;
    #define LEN 100 //long enough for your line
    main(){
       int i;
       string array[4];
    
       for(i = 0; i < 4; i++) {
          if((array[i] = (char *)(malloc(sizeof(char) * LEN))) == NULL) {
              printf("malloc failed");
              return 1;
          }
       } 
    
       FILE *my;
       my = fopen("my.txt","r");
       for(i = 0; i < 4; i++)
             fscanf(data, "%s", &array[i]);
       fclose(my);
    }
    

    And like they said you made space for the pointers but not for what the pointers point to.

提交回复
热议问题