打印到控制台,然后创建文件并将控制台内容打印到文件中

print to console then create file and print console content into file

本文关键字:文件 打印 控制台 创建 然后      更新时间:2023-10-16
#include <iostream>
#include <ostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
void GetOutputFileStream(std::ofstream * fout, std::string filename);
void PrintStatistics(std::ostream & fout,
int numUsed,
int numNew,
double newTotalPrice,
double newTotalMileage,
double usedTotalPrice,
double usedTotalMileage);
int main()
{

double newTotalPrice = 33333;
double newTotalMileage = 44444;
double usedTotalPrice = 22222;
double usedTotalMileage = 99999;
int numUsed = 2;
int numNew = 3;
std::ofstream fout; // 'f'ile out - fout
std::string filename = "statistics.txt";
GetOutputFileStream(&fout, filename);
// Print to screen
PrintStatistics(std::cout,
    numUsed,
    numNew,
    newTotalPrice,
    newTotalMileage,
    usedTotalPrice,
    usedTotalMileage);
// Print to file
PrintStatistics(fout,
    numUsed,
    numNew,
    newTotalPrice,
    newTotalMileage,
    usedTotalPrice,
    usedTotalMileage);

std::cout << "Press ENTER to continue";
std::cin.get();
return 0;
}
void GetOutputFileStream(std::ofstream * fout, std::string filename)
{
    fout->open(filename, std::ios::out);
}
void PrintStatistics(std::ostream & fout,
int numUsed,
int numNew,
double newTotalPrice,
double newTotalMileage,
double usedTotalPrice,
double usedTotalMileage)
{

}

我真的被困在作业的这个特定部分,它要求我将简单的文本打印到控制台中,然后创建一个文件(无论 std::string 文件名可能在主文件中(并将控制台的内容打印到该文件中。

我真的很困惑,因为该函数需要 ostream,并且它还要求该函数使用任何文件名(在此示例中为统计信息.txt进行操作,只是为了测试函数是否正常工作(。

该函数是打印统计。

我知道我可以使用 cout 打印到控制台上,然后我认为 fout 会打印到文本文件中,但事实并非如此。谁能指出我正确的方向?我是这个社区的新手,所以我希望我的问题有意义/代码清晰易读。谢谢!

从概念上讲,ofstream 派生自 ostream 系统,允许您在使用ostream的任何地方使用ofstream

虽然我还没有对此进行测试,但您应该能够在使用输出文件方法的fout时摆脱,作为打印方法ostream参数的参数。

由于foutostream的派生版本,因此打开的文件的内容及其数据将随之传递,这意味着如果ostream的参数是fstream类型,它将在文件中而不是控制台中运行。

在应用程序评估器周围的包装器中执行此类操作比在后者内部执行此类操作比平时要多。说

<myApplication> <arguments> | tee <output_filename>

(在类似 Linux 的 shell 中(会将控制台输出副本带到文件中。