C++循环算法不正确(或文件处理问题)

C++ Incorrect Looping Algorithm (or file processing issue)

本文关键字:文件 处理问题 循环 算法 不正确 C++      更新时间:2023-10-16

我正在尝试制作一个程序,读取文本文件,进行一些数学运算,显示答案,然后编写文本文件。该程序目前只写一行文本,而不是我想要的5行。

输入文本文件的格式如下:

    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行写到FinalOutput.txt

在行中:

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

每次要写一行时,都会打开输出文件。这将截断文件(即删除内容)。

您可以每次以追加模式打开文件,或者更好的是,在函数外打开一次文件,然后通过引用将流对象传递到outputLine函数中。