【发布时间】:2013-04-05 07:21:45
【问题描述】:
似乎总是应该没问题的事情对我造成问题。我不明白。 :/
所以我试图确保我了解如何操作文本文件。我有两个文件,“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
它回来了,但几乎不像我希望的那样。知道为什么会这样吗?为什么我的前 3 次尝试都失败了?
【问题讨论】:
-
什么是
infile.txt?具体来说,数字是多少? -
@Tushar 更重要的是,除了数字之外,它的内容是什么。必须有更多,因为您需要空格来分隔数字。如果文件以
'\n'结尾(如果它是文本文件,则应该这样),那么除了他使用的第一种方法外,其他所有方法都受到标准的保证(第一种方法也可以在实践中使用)。 -
他使用的编译器/库也很重要。 C++11 对
seekg的定义与 C++03 不同。 -
infile.txt: 1\n 2\n 5\n 4\n 1\n 9 使用 MS Visual C++ 2010