期待帮助...我需要从文本文件中读取两个字符串并将它们存储到两个单独的数组中。我搜索了很多代码,其中一个有效,所以我尝试修改它以读取两个字符串。这是我的代码:
int main(){
int i = 0;
int BUFSIZE = 1000;
char* words[20];
char* words2[20];
FILE *fp = fopen("input1.txt", "r");
FILE *fp2 = fopen("input2.txt", "r");
if (fp == 0){
fprintf(stderr, "Error while opening");
return 0;
}
words[i] = (char*)malloc(BUFSIZE);
words2[i] = (char*)malloc(BUFSIZE);
while (fgets(words[i], BUFSIZE, fp)) {
i++;
words[i] = (char*)malloc(BUFSIZE);
}
while (fgets(words2[i], BUFSIZE, fp2)) {
i++;
words2[i] = (char*)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<i; x++)
free(words[x]);
free(words2[x]);
scanf("%d", x);
fclose(fp);
fclose(fp2);
return 0;
}
但它不会工作。有人知道为什么吗?谢谢!