从另一个文件读取时写入文件

时间:2012-11-01 20:31:38

标签: c++ file-io stream

我们可以在函数中同时使用输入文件的元素,同时可以在输出文件中写入结果吗?

语句为真?

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();
}

2 个答案:

答案 0 :(得分:2)

while(!inputFile.eof())

效果不佳,因为它测试上一个操作是否失败,而不是下一个操作失败。

而是尝试

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

}

您测试每个输入操作是否成功,并在读取失败时终止循环。

答案 1 :(得分:1)

您可以,输入和输出流彼此独立,因此在语句中将它们混合在一起没有综合效果。