2013-04-17 4 views
0

Я пытаюсь взять два отсортированных файла с целыми числами 5000 и объединить их в один файл из 10000 отсортированных int. Я работаю, за исключением случаев, когда программа заканчивает один из файлов, распечатывая остальную часть другого файла.Объединение двух отсортированных файлов с помощью 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 

Я знаю, что есть что-то делать с захватом следующей строки из файла и процедурой моего алгоритма. Любые идеи о том, как я могу это исправить?

ответ

1

Я решил проблему. Я не выводил последнее целое число в файл, когда он достигает конца. Я дважды дублировал целое число другого файла, один раз, когда первый файл закончился, и второй раз, когда файл был ложным. Вот как я это решил:

void mergeFiles(string inFile1, string inFile2, string outFile) { 
    // Open Files 
    ifstream fin(inFile1); 
    ifstream fin2(inFile2); 
    ofstream fout(outFile); 

    string line;    // string to hold line from file 
    int i = 1;     // line counter 
    int in2 = 0, in1 = 0;  // ints to hold ints from each file 
    if(fin) {     // if file is open 
     getline(fin,line);  // get first line 
     in1 = atoi(line.c_str()); // convert to int 
    } 
    if(fin2) {     // if file is open 
     getline(fin2,line);  // get first line 
     in2 = atoi(line.c_str()); // convert to int 
    } 
    bool first = true;   // bool to catch when a file closes 
    while(fin || fin2) {  // if either file is still open 
     if(fin && fin2) {  // if both files are still open 
      if(in2 <= in1) { // file 2 has the smaller int 
       fout << i++ << ": " << in2 << endl; // print file 2 int to output file 
       getline(fin2, line);  // get next line from file 2 
       in2 = atoi(line.c_str()); // convert to int 
      } 
      else {    // file 1 has smaller int 
       fout << i++ << ": " << in1 << endl; // print file 1 int to output file 
       getline(fin, line);   // get next line from file 1 
       in1 = atoi(line.c_str()); // convert to int 
      } 
     }//endif 
     else {  // if one of the files has finished 
      if(first) {  // first time through the else 
       if(!fin)  fout << i++ << ": " << in2 << endl;  // Depending on which file closed 
       else if(!fin2) fout << i++ << ": " << in1 << endl;  // print the int before printing lines 
      }//endif 
      else 
       fout << i++ << ": " << line << endl; // don't need to convert just print at this point 

      // get the next line from the file that is open 
      if(fin)   getline(fin, line); 
      else if(fin2) getline(fin2, line); 

      first = false; // only print line from now on, don't print in1 or in2 
     }// endelse 
    }//endwhile 
}//endmethod 
Смежные вопросы