2014-09-21 116 views
2

我有一個任務,我應該讀取包含整數(每行一個)的多個文件,並在排序後將它們合併到輸出文本文件中。我是C++的新手,所以我不知道一切是如何工作的。我正在用兩個.txt文件測試我的程序。第一個文件叫做fileone.txt,包含1,2,7(我不知道如何格式化,但它們全都在不同的行上)。第二個文件叫做filetwo.txt,包含1,3,5, 9,10(每個整數都在不同的行上)。使用ifstream從文本文件打印整數

我寫了下面的代碼,它打開這兩個文件並打印內容。

#include <iostream> 
#include <fstream> 
using namespace std; 

int main(int argc, char** argv) { 

    ifstream iFile; 
    ifstream jFile; 
    iFile.open("fileone.txt"); 
    jFile.open("filetwo.txt"); 

    int int1 = 0; 
    int int2 = 0; 
    if (iFile.is_open() && jFile.is_open()){ 


     while (iFile.good() || jFile.good()) { 

      iFile >> int1; 
      jFile >> int2; 

      cout << "From first file:" << int1 << endl; 
      cout << "From second file:" << int2 << endl; 

     } 
    } 

    iFile.close(); 
    jFile.close(); 

    return 0; 
} 

這個程序的輸出是 enter image description here

我遇到的問題是在第一個文件的最後一個號碼被打印多次。我想要的輸出是在打印文件中的最後一個整數後停止打印。該問題僅在第二個文件包含比第一個文件多的整數時纔會出現。是否有辦法在第一個文件到達最後時停止打印,同時仍然打印第二個文件中的所有數字?

回答

6

這將這樣的伎倆

while (iFile || jFile) { 

     if(iFile >> int1) // make sure the read succeeded!! 
      cout << "From first file:" << int1 << endl; 

     if(jFile >> int2) // make sure the read succeeded!! 
      cout << "From second file:" << int2 << endl; 
    } 

,如果你檢查,看它是否被成功讀取時,才應真正使用的數據。

+0

啊,是的。這是我的回答中提到的更好的成語。 – 2014-09-21 03:52:20

0

考慮更改環路跟隨

while (iFile.good() || jFile.good()) { 
    iFile >> int1; 
    jFile >> int2; 
    int c = iFile.peek(); 
    int d = jFile.peek(); 
    if (c == EOF) { 
     if (!iFile.eof()) 
     cout << "From first file:" << int1 << endl; 
    } 
    if (d == EOF) { 
     if (!jFile.eof()) 
     cout << "From second file:" << int2 << endl; 
     } 
    } 

的事情是檢查文件的末尾和處理,如果將其打印出來。您可以使用eof()函數如上。

我還沒有檢查過代碼。但邏輯應該是正確的。

+2

不必要的複雜 – P0W 2014-09-21 02:12:01

+0

@Nabin沒有真正必要的改進。它仍然太複雜了! – 2014-09-21 03:54:03