【问题标题】:print to console then create file and print console content into file打印到控制台然后创建文件并将控制台内容打印到文件中
【发布时间】:2015-11-18 04:35:48
【问题描述】:
#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 文件名可能在 main 中)并打印控制台的内容进入那个文件。

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

函数是 PrintStatistics。

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

【问题讨论】:

    标签: c++


    【解决方案1】:

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

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

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

    【讨论】:

    • 我使用 fout,但它的操作类似于 cout。例如,我会在 PrintStatistics 中按顺序使用 cout 和 fout,但它会在控制台中同时打印 fout 和 cout 而文件中什么也没有。感谢您抽出宝贵时间回复!
    • @alekbiz 尝试更改您的 GetOutputFileStream 方法以在打开文件后调用 INSIDE 打印方法,看看是否有区别。以您现在的方式,您的fout 的范围和对文件的操作可能存在问题。
    • 如果您指的是 main() 中的代码,我无法更改它,因为这是教师让我们用来测试我们的功能的具体代码。
    • 我的错误,我假设你的意思是重新工作 GetOutputFileStream,对吗?
    • @alekbiz 是的,GetOutputFileStream 方法本身,而不是 main
    【解决方案2】:

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

    <myApplication> <arguments> | tee <output_filename>
    

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

    【讨论】:

    • 该方法的名称是什么?所以我可以寻找更多关于它的信息。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2021-12-06
    • 2019-08-22
    相关资源
    最近更新 更多