我正在尝试创建一个带有数组'inputLayer []'的函数,并将数组中的每个元素存储在单个文件中。第一次调用该函数时,它应该创建文件,并且在调用它时,它应该将inputLayer中的新元素追加到文件的末尾。
如果我在一个文件中重复存储一个变量,我会使用这样的东西:
int recordInputVariables(double inputLayer[])
{
for(int i = 0; i < inputLayerSize; i ++)
{
stringstream ss;
ss << i;
string inputNumberString = ss.str();
string recordFileName = "input_";
recordFileName.append(inputNumberString);
recordFileName.append("_record.txt");
fstream inputRecordFile( recordFileName.c_str() );
inputRecordFile.open (recordFileName, fstream::in | fstream::out | fstream::app);
inputRecordFile << inputLayer[i] << endl;
inputRecordFile.close();
}
return 0;
}
过去那对我有用,但现在我有很多变量,我想写给名为“input_0_record.txt”,“input_1_record.txt”的个别文件,等等。
在下面的代码中,我使用stringstream创建文件名,然后使用与上面相同的方法将变量写入其文件中。
WinForms
但是,当我运行它时,文件被创建,并且在第一次调用函数时将变量写入文件,但随后调用该函数时,没有新的变量写入文件。
我几乎可以肯定我打开文件的方式存在问题。谁能发现我做错了什么?
答案 0 :(得分:2)
inputRecordFile.open (recordFileName, fstream::out | fstream::app);
请勿在此上下文中使用fstream::in
。
答案 1 :(得分:1)
您可以将相同的问题编码为:
int recordInputVariables(double inputLayer[])
{
for(int i = 0; i < 5; i ++)
{
stringstream ss;
ss << i;
string inputNumberString = ss.str();
string recordFileName = "input_";
recordFileName.append(inputNumberString);
recordFileName.append("_record.txt");
cout << recordFileName << endl;
ofstream inputRecordFile(recordFileName.c_str());
// Here you have opened file by using constructor(above) so don't
// need to open it again as below
// inputRecordFile.open (recordFileName, ofstream::out);
inputRecordFile << inputLayer[i] << endl;
inputRecordFile.close();
cout << "loop" << endl;
}
return 0;
}
现在你运行这段代码,一切都会按照你的意愿......