Reading from a file and storing in array

后端 未结 4 610
刺人心
刺人心 2020-12-09 01:00

I\'ve written the following program to read line by line from a file and store it in the words array. The output should be two random words from the array. But surprisingly

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 01:10

    int main(){
     int i = 0;
    
     int BUFSIZE = 1000;
     char* words[20];
     FILE *fp = fopen("input.txt", "r");
     if (fp == 0){
            fprintf(stderr, "Error while opening");
            exit(1);
     }
    
     words[i] = malloc(BUFSIZE);
      while (fgets(words[i], BUFSIZE, fp)) {
            i++;
            words[i] = malloc(BUFSIZE);
     } 
     printf("Output: \n");
     srand(time(NULL));
     int j = rand()%i;
     int k = (j+1)%i;
     fflush(stdout);
     printf("%d - %s %d -%s", j, words[j], k, words[k]); 
    
     int x;
     for(x = 0; x

    ps. Check malloc result

提交回复
热议问题