2012-11-01 97 views
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(); 
} 
+1

你有试过吗?我认为它应该工作。 – Xymostech

+0

您可能想阅读关于RAII(资源获取是初始化)。你的close语句或者是多余的(如果文件关闭了)或者不是异常安全的(如果文件没有关闭,那么close语句在异常情况下不会被执行,这可能会导致问题)。我猜你的代码可以通过销毁流对象来关闭文件,但是你应该明白为什么close语句可以被删除。 – JohnB

+2

请勿使用'eof()'。这从来都不正确。每天大约有200人在StackOverflow上得到这个错误... –

回答

1

可以,输入和输出流是相互独立的,所以它们混合在一起在语句中不具有组合效果。

2
while(!inputFile.eof()) 

不能很好地工作,因为它测试,如果以前操作失败,如果没有下一个会是成功的。

而是尝试

while(inputFile >> number) 
{ 
    outputFile << number*100 << "\n" 
    // do something 

} 

,你测试成功,每个输入操作,当读取失败终止循环。

相关问题