按升序组合2个int文件,比较它们,然后将它们排序到第三个文件中,而不使用c中的数组



我试图在2 .txt文件中读取包含按升序排序的整数到第三个,我不能使用数组。它部分工作,然后打印无限量的正方形。我认为当代码到达其中一个文件的末尾时,这是一个问题。

#include <stdio.h>
#include <stdlib.h>
int main() 
{
    FILE *n1, *n2, *op;
    int c, d;
    n1 = fopen("numbers1.txt", "r");
    n2 = fopen("numbers2.txt", "r");
    op = fopen("output.txt", "w");
    c = fgetc(n1);
    d = fgetc(n2);
    while (1 )
    {
        if (c == EOF && d == EOF)
            break;
        else if (c<d )
        {
            putc(c, op);
            c = fgetc(n1);
        }
        else if(d<c )
        {
            putc(d,op);
            d = fgetc(n2);
        }
        else if(d == c )
        {
            putc(c, op);
            c = fgetc(n1);
        }
        else if (c == EOF && d != EOF )
        {
            putc(d,op);
            d = fgetc(n2);
        }
        else if (c != EOF && d == EOF )
        {
            putc(c, op);
            c = fgetc(n1);
        }
    }
    fclose(n1);
    fclose(n2);
    fclose(op);
}
#include <stdio.h>
#include <stdlib.h>
int main(void){
    FILE *n1, *n2, *op;
    int st1, st2;
    int c, d;
    n1 = fopen("numbers1.txt", "r");
    n2 = fopen("numbers2.txt", "r");
    op = fopen("output.txt", "w");
    st1 = fscanf(n1, "%d", &c);
    st2 = fscanf(n2, "%d", &d);
    while(1){
        if(st1 == EOF && st2 == EOF)
            break;
        if(st1 != EOF && st2 != EOF){
            if(c < d){
                fprintf(op, "%dn", c);
                st1 = fscanf(n1, "%d", &c);
            } else if(c > d){
                fprintf(op, "%dn", d);
                st2 = fscanf(n2, "%d", &d);
            } else {
                fprintf(op, "%dn%dn", c, d);
                st1 = fscanf(n1, "%d", &c);
                st2 = fscanf(n2, "%d", &d);
            }
        } else if(st1 != EOF){
            fprintf(op, "%dn", c);
            st1 = fscanf(n1, "%d", &c);
        } else {
            fprintf(op, "%dn", d);
            st2 = fscanf(n2, "%d", &d);
        }
    }
    fclose(n1);
    fclose(n2);
    fclose(op);
    return 0;
}

最干净的方法是编写三个单独的循环:

// Do the main loop until you reach the end of one of the files
while (!(c == EOF && d == EOF))
{
    // do your stuff here
}
// At this point, at least one of the files is at EOF.
// You want to drain the other
// Note that only one of the two loops will be entered.
while (c != EOF)
{
    // copy the remaining contents of the first file to the output
}
while (d != EOF)
{
    // copy the remaining contents of the second file to the output
}

我知道,它看起来像更多的代码。但是你没有在循环中检查所有的if语句,看看你是否在第一个文件的末尾,而不是在另一个文件的末尾,等等。以上内容更容易理解,并且在创建时更有可能正确使用。

最新更新