使用 Gecode 打印到文件
Printing to file using Gecode
我正在做一个 Gecode 项目,代码应该输出一个如下所示的文件:
n: 17
x: {0, 0, 16, 18, 17, 31, 32, 0, 34, 10, 30, 37, 38, 30, 30, 10}
y: {0, 27, 28, 14, 0, 31, 20, 17, 11, 17, 0, 0, 6, 7, 11, 25}
s: 43
runtime: 0.137
failure: 127
以上是代码应输出的示例。我尝试执行以下代码:
virtual void
print(std::ostream& os) const {
string filename = "project1-t15-n" + n + ".txt";
ofstream myfile;
myfile.open (filename);
myfile << "n: " << n << std::endl;
myfile << "x: {";
for (int i = 0; i < x.size(); i++) {
if (i != 0) {
myfile << ", ";
}
myfile << x[i];
}
myfile << "}" << std::endl;
myfile << "y: {";
for (int i = 0; i < y.size(); i++) {
if (i != 0) {
myfile << ", ";
}
myfile << y[i];
}
myfile << "}" << std::endl;
myfile << "s: " << s << std::endl;
//???????????????????????????????? print runtime and failures
myfile.close();
}
我知道 n、s、x 和 y 是正确的,但我有两个问题:
1:打印到文件时print(std::ostream& os) const
正确的用法吗?
2:如何从 Gecode 输出中获取运行时和故障?他们的内置打印功能就是这样做的。
myfile << "s: " << s << std::endl;
我在你的代码中没有看到任何s
,它是什么?此外,打印方法的签名表明它已经获取了输出流。这是真的吗?谁叫它,从哪里来,用什么论点?如果其他方法确实调用 print 并为其提供输出流,那么您可能应该使用它,而不是创建自己的方法。
更新:查看了 Gecode 的文档,找到了定义 print() 的地方:
http://www.gecode.org/doc-latest/reference/driver_8hh_source.html#l00666
因此,您可以在自己的类中重新定义此方法,该方法源自 ScriptBase(我想这就是您应该为 Gecode 编写内容的方式),但您应该使用提供的参数,即:
virtual void
print(std::ostream& os) const {
os << "n: " << n << std::endl;
os << "x: {";
// etc
实际打印到特定文件 I/O 控制台的一个选项是简单地使用重新路由的输出运行程序。 例如,如果您的程序称为myprogram,而您的文件称为myfile.txt,请按以下方式运行它:
myprogram >> myfile.txt
它会将所有内容打印到文件而不是控制台。
另外,就文档(http://www.gecode.org/doc-latest/MPG.pdf)而言,如果您有 ScriptBase 派生的类 S,您可以直接从 main() 方法调用其方法 S->print(),并在那里提供正确的文件流,即:
S* s= new S; // something like that
ofstream f("myfile.txt");
s->print(f);
...
- 使用 getline 从输入文件打印时如何忽略空白行
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 如何将文件打印到其他文件夹
- 如何修复向量不从文件打印值
- 从文本文件打印后如何摆脱新线条,并在打印时摆脱结局空间
- 使用数组从文件打印整数
- 从文本文件打印 sfml 中的 2D 数组
- 从输入文件打印图形
- 从C 中的.txt文件打印出所选的数据
- 超载Ostream运算符从文件打印矩阵
- 为什么这不从TXT文件打印值
- 从文本文件打印字符串和整数 (C++)
- 为什么它只打印文本文件的一个单词,而不是将整个文本文件打印到html文件中
- C++从文本文件打印回文
- 无法从文件打印文本
- 尝试从输入文件打印,但打印最后一个输入两次
- 在 c++ 中从文件打印 2D 数组
- 从 postgresql 上运行的 c++ 文件打印
- 获取字符串从文本文件打印随机行时出现问题