2016-05-02 20 views
0

我試圖做一個程序,讀取文本文件,做一些數學,顯示答案,然後寫入文本文件。該程序目前只寫一行文本,而不是我想要的5行。C++不正確的循環算法(或文件處理問題)

輸入文本文件被格式化爲這樣:

string double double 
    string double double 
    string double double 
    string double double 
    string double double 

輸出文本文件變成這樣: 字符串,雙,雙,雙,

它寫出我想要的東西,但只有一次。 我想要它處理所有5行。我的程序只處理輸入文本文件的最後一行。

這是輸入文本文件的樣子(只是沒了文件名)

//payinfile.txt 
    2198514 17.20 11.25 
    6698252 59.25 21.00 
    5896541 50.00 10.00 
    8863214 45.00 18.20 
    8465555 25.75 14.80 

,這裏是我的程序

// outputprogram.cpp 
    #include <iostream> 
    #include <fstream> // file stream 
    #include <iomanip> 
    #include <string> 
    #include <cstdlib> // exit function prototype 
    using namespace std; 

    void outputLine(const string, double, double); // prototype 
    // void writeToFile(); 

    int main() 
    { 
     // ifstream constructor opens the file   
     ifstream inputFile("payinfile.txt", ios::in); 

     // exit program if ifstream could not open file 
     if (!inputFile) 
     { 
      cerr << "File could not be opened" << endl; 
      exit(EXIT_FAILURE); 
     } // end if 

     string ID; // the account number 
     double hours; // the account owner's name 
     double rate; // the account balance 

     cout << left << setw(10) << "ID" << setw(15) 
      << "Hours" << setw(10) << "Rate" << right << setw(10) << "Gross" << endl << fixed << showpoint; 

     // display each record in file 
     while (inputFile >> ID >> hours >> rate) 
     { 
      outputLine(ID, hours, rate); 
     } 

    } // end main 

    // display single record from file 
    void outputLine(const string ID, double hours, double rate) 
    { 
     double gross; 
     gross = 0.0; 
     gross = (hours * rate); 

     cout << left << setw(10) << ID 
      << setw(15) << hours 
      << setw(15) << setprecision(2) << rate 
      << setw(10) << setprecision(2) << gross << endl; 

     // ofstream constructor opens file     
     ofstream writeToFile("FinalOutput.txt", ios::out); 

     // exit program if unable to create file 
     if (!writeToFile) // overloaded ! operator 
     { 
      cerr << "File could not be opened" << endl; 
      exit(EXIT_FAILURE); 
     } // end if 

     writeToFile << ID << ", " << hours << ", " << rate << ", " << gross << ", "; 


    } // end function outputLine 

代碼執行後,這是輸出文件看起來像:

//FinalOutput.txt 
    8465555, 25.75, 14.8, 381.1, 

所以它寫我想要的,我也想它也寫其他4行s到FinalOutput.txt

+0

TheDark回答了你的問題,但我想指出'cerr <<「文件行無法打開<< << endl;'是一個不適當的錯誤信息。它應該按照在流構造函數中使用的文件名稱(在本例中爲「FinalOutput.txt」),更重要的是,'strerror(errno)'。 – zwol

回答

3

在這一行:

ofstream writeToFile("FinalOutput.txt", ios::out); 

你打開你想要寫一行每次輸出文件。這會截斷文件(即刪除內容)。

您可以每次都以追加模式打開文件,或者更好的是,在函數外部打開文件一次,並通過引用將流對象傳遞給outputLine函數。