Ant*_*Ant 3 c++ string streaming iostream
我编写了用于执行计算的C++代码.代码中有一个循环.在每个循环结束时,我想:
1)获取时间,计算结果.
2)为文件命名.名称应包含时间.
3)将文件名打印到外部文件中.每个新循环都应覆盖上一循环中的文件名.
我遇到的第一个问题是我无法删除OLD文件名.所以当我的计算结束时,名称是(例如):calculationForRestartFile_0.0005476490.004925880.01763170.04375820
而不是:calculationForRestartFile_04375820
我已经更新了这个问题以纳入Mat的建议.谢谢你.但是现在我在外部文件中没有得到任何东西.谁能看到我哪里出错了?我会非常感谢任何建议.
// Above loop:
std::string filename = "calculationForRestartFile_"; // Part of the file name that ALL files should have
ofstream fileNameAtHighestTimeStream;
std::string convertedToString; // This and the line below:
std::stringstream storeNumberForConversion; // For storing a loop number/time as a string
// Inside loop:
storeNumberForConversion << global_time << flush; // Turn the time/loop number into a string that can be added to the file name for a particular loop
convertedToString = storeNumberForConversion.str();
fileNameAtHighestTimeStream.open ("externalFile", ios::out | ios::app );
fileNameAtHighestTimeStream << filename << convertedToString << endl; // Append the time/loop name to the file name and write to the external file
fileNameAtHighestTimeStream.close();
// End loop
Run Code Online (Sandbox Code Playgroud)
问题是这一行正在添加到你stringstream的循环内部.你永远不会重置其内容.
storeNumberForConversion << global_time << flush;
Run Code Online (Sandbox Code Playgroud)
最简单的方法是移动storeNumberForConversion循环内部的声明,以便在使用之前将其创建为空.
或者,您可以在格式化操作后重置它.
storeNumberForConversion.str( std::string() );
Run Code Online (Sandbox Code Playgroud)