【发布时间】:2014-12-01 09:31:28
【问题描述】:
我有一个这样声明的变量: sc_bigint x
我想使用 fprintf 将其打印到文件中,但这会产生错误。 我可以使用 cout 打印变量,但我需要将它打印到我打开的特定文件中。
任何想法如何做到这一点? 也许是一种将 cout 重定向到我需要的文件的简单方法?
【问题讨论】:
我有一个这样声明的变量: sc_bigint x
我想使用 fprintf 将其打印到文件中,但这会产生错误。 我可以使用 cout 打印变量,但我需要将它打印到我打开的特定文件中。
任何想法如何做到这一点? 也许是一种将 cout 重定向到我需要的文件的简单方法?
【问题讨论】:
试试 C++ 提供的文件 I/O 流。
#include <fstream>
#include <iostream>
using namespace std;
// .. snip
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
sc_bigint<88> x;
outfile << x;
【讨论】:
使用 C++ 的基于流的 IO(如另一个答案所示)可能是最好的方法,但是,如果您真的想使用 fprintf(),那么您可以选择使用 sc_dt::sc_bigint<W>::to_string() 方法。例如:
#include <systemc>
#include <cstdio>
using namespace std;
int sc_main(int argc, char **argv) {
FILE *fp = fopen("sc_bigint.txt", "w");
sc_dt::sc_bigint<88> x("0x7fffffffffffffffffffff"); // (2 ** 87) - 1
fprintf(fp, "x = %s (decimal)\n", x.to_string().c_str());
fprintf(fp, "x = %s (hexadecimal)\n", x.to_string(sc_dt::SC_HEX).c_str());
return EXIT_SUCCESS;
}
上述 SystemC 程序将以下内容写入文件sc_bigint.txt:
x = 154742504910672534362390527 (decimal)
x = 0x7fffffffffffffffffffff (hexadecimal)
【讨论】: