3
我们可以在使用输入文件的元素的同时在函数中同时执行这两个操作吗?我们可以在输出文件中同时写入结果吗?从另一个文件读取时写入文件
里面的而声明是真的吗?
void solve(string inputFileName, string outputFileName)
{
//declaring variables
string filename = inputFileName;
//Open a stream for the input file
ifstream inputFile;
inputFile.open(filename.c_str(), ios_base::in);
//open a stream for output file
outputfile = outputFileName;
ofstream outputFile;
outputFile.open(outputfile.c_str(), ios_base::out);
while(!inputFile.eof())
{
inputFile >> number; //Read an integer from the file stream
outputFile << number*100 << "\n"
// do something
}
//close the input file stream
inputFile.close();
//close output file stream
outputFile.close();
}
你有试过吗?我认为它应该工作。 – Xymostech
您可能想阅读关于RAII(资源获取是初始化)。你的close语句或者是多余的(如果文件关闭了)或者不是异常安全的(如果文件没有关闭,那么close语句在异常情况下不会被执行,这可能会导致问题)。我猜你的代码可以通过销毁流对象来关闭文件,但是你应该明白为什么close语句可以被删除。 – JohnB
请勿使用'eof()'。这从来都不正确。每天大约有200人在StackOverflow上得到这个错误... –