0
我想將兩個有5000個整數的已排序文件合併成一個10000個整數整數的文件。我有它的工作,除非程序完成其中一個文件,打印出其他文件的其餘部分。用fstream合併兩個排序的文件
這裏是我的方法來合併兩個文件
void mergeFiles(string inFile1, string inFile2, string outFile) {
ifstream fin(inFile1);
ifstream fin2(inFile2);
ofstream fout(outFile);
string line;
int i = 1;
int in2 = 0, in1 = 0;
if(fin) {
getline(fin,line);
in1 = atoi(line.c_str());
}
if(fin2) {
getline(fin2,line);
in2 = atoi(line.c_str());
}
bool first = true;
while(fin || fin2) {
if(fin && fin2) {
if(in2 <= in1) {
fout << i++ << ": " << in2 << endl;
getline(fin2, line);
in2 = atoi(line.c_str());
}
else {
fout << i++ << ": " << in1 << endl;
getline(fin, line);
in1 = atoi(line.c_str());
}
}
else {
// This is the part giving me trouble
// Code Snippets below go here
}
}
}
根據我使用這個:
fout << i++ << ": " << line << endl;
if(fin)
getline(fin, line);
else if(fin2)
getline(fin2, line);
最後5行我輸出的文件是這樣的:
9996: 99933
9997: 99943
9998: 99947
9999: 99947
10000: 99993
或
if(fin)
getline(fin, line);
else if(fin2)
getline(fin2, line);
fout << i++ << ": " << line << endl;
最後5行我的文件是這樣的:
9996: 99933
9997: 99943
9998: 99947
9999: 99993
10000: 99993
最後5行我的文件都應該是這樣的:
9996: 99933
9997: 99943
9998: 99947
9999: 99957
10000: 99993
我知道這事做從文件中抓取下一行以及我的算法的過程。關於如何修復它的任何想法?