期待帮助...我需要从文本文件中读取两个字符串并将它们存储到两个单独的数组中。我搜索过,得到了很多代码,其中一个有效,所以我试着修改它来读两个字符串。这是我的代码:
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;
}
但它不起作用。任何人都知道为什么?谢谢!
答案 0 :(得分:2)
在第二次循环之前重置i = 0并使用花括号
包含你的免费(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;
}
答案 1 :(得分:0)
需要更多关于正在发生的事情的信息。您是否收到编译错误,运行时消息?你检查过这些文件了吗?
此外,还应修改一些事项:
您的第一行应包含stdio.h
在for()的主体周围添加大括号,以包含两个免费通话。
您的编译器是否接受函数中间的x声明?如果没有,请将其移至顶部。