我有 2 个 txt 文件,其中数字 > 0,我必须对它们进行组合和排序。也不能有 2 个相同的值。
这里是文件的值。 文件 1:
1
2
3
4
5
6
7
文件2:
1
3
6
8
10
输出应该是这样的:
1
2
3
4
5
6
7
8
10
我目前的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fr1,*fr2;
int fst, snd, p[256], i=0, n=0;
bool f1=true,f2=true;
fr1 = fopen("txt/cisla.txt","r");
fr2 = fopen("txt/cisla2.txt","r");
while(feof(fr1) == 0 && feof(fr2) == 0)
{
if (f1) fscanf(fr1, "%d", &fst);
if (f2) fscanf(fr2, "%d", &snd);
printf("%d - %d\n", fst, snd);
if (fst == snd)
{
f1 = true;
f2 = true;
p[i] = fst;
} else if (fst > snd)
{
p[i] = snd;
f1 = false;
f2 = true;
} else
{
f2 = false;
f1 = true;
p[i] = fst;
}
i++;
}
fclose(fr1);
fclose(fr2);
printf("\n\n\n");
for(int j = 0; j < i; j++)
{
printf("%d\n", p[j]);
}
return 0;
}
结果是:
1 - 1
2 - 3
3 - 3
4 - 6
5 - 6
6 - 6
7 - 8
1
2
3
4
5
6
7
底部是数组。在顶部,我写的是读取的值。问题是它似乎在第一个文件的末尾停止,但我希望它继续第二个,即使第一个文件在末尾p>
最佳答案
The thing is it seems to stop at the end of the first file
那是因为你告诉它这样做 - 你拥有的继续条件是两个 feof
都返回零:
while(feof(fr1) == 0 && feof(fr2) == 0) {
...
}
I want it to continue the second one even if the first one is at the end
在第一个循环之后再添加两个循环,用较大的元素写出文件的“尾部”:
while(feof(fr1) == 0 && feof(fr2) == 0) {
... // Do the merge
}
while(feof(fr1) == 0) {
... // Read from fr1, and write to the output
}
while(feof(fr2) == 0) {
... // Read from fr2, and write to the output
}
关于c++ - 合并 2 个文件并对它们进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20665262/