c - 如何从文件读取两个字符串并将它们存储在两个单独的数组中

标签 c arrays string input output

期待帮助...我需要从文本文件中读取两个字符串并将它们存储到两个单独的数组中。我搜索过,得到了很多代码,其中之一有效,所以我尝试修改它以读取两个字符串。这是我的代码:

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/

相关文章:

c - libcurl 即时压缩下载的数据

c - C 中 float 据类型的格式说明符

javascript - 如何将用户输入存储到数组中?

arrays - 显示数组的索引 - Angular 4+

c - 每行打印一个字

Java StringBuilder追加长字符串错误

c - 为什么指针中包含的内存地址和指针的地址相同?

c - 为什么选择报告读取文件描述符不断准备就绪?

javascript - 根据值对具有键值对的对象进行排序

c - C语言中的字符串指针