似乎总是对我造成问题的事情应该没问题。我不明白。:/
所以我试图确保我了解如何操作文本文件。我有两个文件,“infile.txt”和“outfile.txt”。“infile.txt”里面有六个数字,没有别的。这是我用来操作文件的代码。
#include<fstream>
using std::ifstream;
using std::ofstream;
using std::fstream;
using std::endl;
using std::ios;
int main()
{
ifstream inStream;
ofstream outStream;//create streams
inStream.open("infile.txt", ios::in | ios::out);
outStream.open("outfile.txt");//attach files
int first, second, third;
inStream >> first >> second >> third;
outStream << "The sum of the first 3 nums is " << (first+second+third) << endl;
//make two operations on the 6 numbers
inStream >> first >> second >> third;
outStream << "The sum of the second 3 nums is " << (first+second+third) << endl;
inStream.seekg(0); //4 different ways to force the program to go back to the beginning of the file
//2. inStream.seekg(0, ios::beg);
//3. inStream.seekg(0, inStream.beg);
//4. inStream.close(); inStream.open("infile.txt");
//I have tried all four of these lines and only #4 works.
//There has got to be a more natural option than just
//closing and reopening the file. Right?
inStream >> first >> second >> third;
outStream << "And again, the sum of the first 3 nums is " << (first+second+third) << endl;
inStream.close();
outStream.close();
return 0;
}
也许我不太了解流的工作原理,但我看到一些消息来源说 seekg(0) 应该将索引移回文件的开头。相反,这就是我从中得到的。
前 3 个数字之和为 8
后 3 个数字之和为 14
再一次,前 3 个数字的总和是 14
它回来了,但几乎不像我希望的那样。知道为什么会这样吗?为什么我的前三个尝试都失败了?