如何在输出文件中创建行?

How do I create rows in an output file?

我目前有这段代码,所有格式都是正确的...我似乎无法让它在输出文本文件中创建行...我该怎么做?我试图在函数和 main() 中做一个 for 循环,但如果我这样做似乎不起作用,所以我现在很困惑。

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

void output(string flightnumber, int arrival1, int arrival2, int realarrival1, int realarrival2, char dummy1, char dummy2)
{
    ofstream flight;
    flight.open("flightdata.dat");

    if (flight.fail())
    {
        cout << "Error..." << endl;
        exit(1);
    }

    cout << "Enter the flight number: ";
    cin >> flightnumber;

    if (flightnumber == "end")
    {
        exit(1);
    }

    flight << flightnumber << setw(4);

    cout << "Enter the scheduled/actual arrival times (hh:mm hh:mm):";

    cin >> arrival1 >> dummy1 >> arrival2 >> realarrival1 >> dummy2 >> realarrival2;
    flight << arrival1 << dummy1 << arrival2 << setw(4) << realarrival1 << dummy2 << realarrival2;
    flight << ('\n');
}

int main()
{
    string flightnumber;
    int arrival1, arrival2, realarrival1, realarrival2;
    char dummy1, dummy2;

    output(flightnumber, arrival1, arrival2, realarrival1, realarrival2, dummy1, dummy2);

    return 0;
}

当您编写文件时,您不会附加您的文件,它会截断并创建一个新文件,添加附加标志并打开您的文件。

flight.open("flightdata.dat", ios_base::app);

您在 main 中使用了未初始化的变量。无论如何,它们在那里毫无用处。从 main 中删除变量声明并将它们放入 output:

void output()
{
    string flightnumber;
    int arrival1, arrival2, realarrival1, realarrival2;
    char dummy1, dummy2;

    ofstream flight;
    flight.open("c:\test\___flightdata.txt", ios::app);
    ...
}

int main()
{
    output();
    return 0;
}

您可能想要添加 ios::app 标志,正如其他答案中指出的那样。