期待帮助...我需要从文本文件中读取两个字符串并将它们存储到两个单独的数组中。我搜索过,得到了很多代码,其中之一有效,所以我尝试修改它以读取两个字符串。这是我的代码:
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;
}
但是它不起作用。有人知道为什么吗?谢谢!
最佳答案
在第二个循环之前重置 i = 0 并将您的 free(x) 代码包含在大括号中
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);
}
// reset i back to zero
i = 0;
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;
}
关于c - 如何从文件读取两个字符串并将它们存储在两个单独的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13318187/