我正在尝试创建由动态索引 (d = {0,...,NUM_DEMES-1}) 下标的输出文件。目前,我只获取第一个值 (d=0) 的输出文件。
#include <sstream>
#include <string>
void Simulation::updateSimulation( double t )
{
...
ofstream abundanceStream;
ofstream abHeaderStream;
if ( step == 1 ) {
for ( int d = 0; d < NUM_DEMES; d++ ) {
abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::out);
abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::out);
}
}
for ( int d = 0; d < NUM_DEMES; d++ ) {
abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::app);
abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::app);
}
}
string Simulation::makeFilename( const string& basename, int index )
{
ostringstream result;
result << basename << index;
return result.str();
}
这会创建 Abundances_0 和 Abundances_IDs_0,但不会创建其他内容。我可以写入那些文件。我可以很好地创建其他文件名,但文件就是不显示。
我可能遗漏了一些关于流的基本知识,但我一直无法弄清楚是什么。
编辑
以下代码打印以筛选正确的文件名:
for ( int d = 0; d < NUM_DEMES; d++ ) {
abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::app);
abundanceStream << "stuff\n";
cout << makeFilename( "Abundances_", d ).c_str() << endl;
abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::app);
abHeaderStream << "more stuff\n";
cout << makeFilename( "Abundances_IDs_", d ).c_str() << endl;
}
但是“东西”和“更多东西”只出现在 Abundances_0 和 Abundances_IDs_0 中。
最佳答案
您总是使用相同的对象。您可以在“使用”后关闭流,也可以为每个文件使用不同的对象。
关于c++ - 动态输出文件名 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1724842/