gpt4 book ai didi

c++ - 如何在 C++ 中重写 cout?

转载 作者:可可西里 更新时间:2023-11-01 13:50:46 25 4
gpt4 key购买 nike

我有一个要求,我需要使用printfcout 将数据显示到控制台和文件 中。对于printf我做到了但是对于cout我很纠结,怎么办?

   #ifdef _MSC_VER
#define GWEN_FNULL "NUL"
#define va_copy(d,s) ((d) = (s))
#else
#define GWEN_FNULL "/dev/null"
#endif
#include <iostream>
#include <fstream>

using namespace std;
void printf (FILE * outfile, const char * format, ...)
{

va_list ap1, ap2;
int i = 5;
va_start(ap1, format);
va_copy(ap2, ap1);
vprintf(format, ap1);
vfprintf(outfile, format, ap2);
va_end(ap2);
va_end(ap1);
}
/* void COUT(const char* fmt, ...)
{
ofstream out("output-file.txt");
std::cout << "Cout to file";
out << "Cout to file";
}*/
int main (int argc, char *argv[]) {

FILE *outfile;
char *mode = "a+";
char outputFilename[] = "PRINT.log";
outfile = fopen(outputFilename, mode);

char bigfoot[] = "Hello

World!\n";
int howbad = 10;

printf(outfile, "\n--------\n");
//myout();

/* then i realized that i can't send the arguments to fn:PRINTs */
printf(outfile, "%s %i",bigfoot, howbad); /* error here! I can't send bigfoot and howbad*/

system("pause");
return 0;
}

我已经在COUT(大写,上面代码的注释部分)中完成了。但我想使用普通的 std::cout,所以我该如何覆盖它。它应该适用于 sting 和变量,比如

int i = 5;
cout << "Hello world" << i <<endl;

或者无论如何都可以捕获stdout 数据,以便它们也可以轻松写入文件和控制台

最佳答案

如果你有另一个流缓冲区,你可以只替换 std::cout 的:

std::cout.rdbuf(some_other_rdbuf);

参见 http://en.cppreference.com/w/cpp/io/basic_ios/rdbuf .

关于c++ - 如何在 C++ 中重写 cout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18975512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com