打印到控制台,然后创建文件并将控制台内容打印到文件中
print to console then create file and print console content into file
#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
参数的参数。
由于fout
是ostream
的派生版本,因此打开的文件的内容及其数据将随之传递,这意味着如果ostream
的参数是fstream
类型,它将在文件中而不是控制台中运行。
在应用程序评估器周围的包装器中执行此类操作比在后者内部执行此类操作比平时要多。说
<myApplication> <arguments> | tee <output_filename>
(在类似 Linux 的 shell 中(会将控制台输出副本带到文件中。
相关文章:
- 使用 getline 从输入文件打印时如何忽略空白行
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 如何将文件打印到其他文件夹
- 如何修复向量不从文件打印值
- 从文本文件打印后如何摆脱新线条,并在打印时摆脱结局空间
- 使用数组从文件打印整数
- 从文本文件打印 sfml 中的 2D 数组
- 从输入文件打印图形
- 从C 中的.txt文件打印出所选的数据
- 超载Ostream运算符从文件打印矩阵
- 为什么这不从TXT文件打印值
- 从文本文件打印字符串和整数 (C++)
- 为什么它只打印文本文件的一个单词,而不是将整个文本文件打印到html文件中
- C++从文本文件打印回文
- 无法从文件打印文本
- 尝试从输入文件打印,但打印最后一个输入两次
- 在 c++ 中从文件打印 2D 数组
- 从 postgresql 上运行的 c++ 文件打印
- 获取字符串从文本文件打印随机行时出现问题