0

私にとって問題を引き起こすのは、常に問題にならないはずのことのようです。理解できません。:/

そのため、テキスト ファイルの操作方法を理解していることを確認しようとしています。「infile.txt」と「outfile.txt」の 2 つのファイルがあります。「infile.txt」には 6 つの数字があり、他には何もありません。ファイルの操作に使用したコードは次のとおりです。

#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 です

2 番目の 3 つの数値の合計は 14 です

繰り返しますが、最初の 3 つの数字の合計は 14 です。

それは元に戻りましたが、私が望んでいたほどではありませんでした. なぜこれが起こったのですか?最初の 3 回の試行が失敗したのはなぜですか?

4

3 に答える 3

2

2 番目の入力は、ストリームのファイルの終わりに達します。inStream.clear()その状態は、(シークに加えて) その状態をクリアするために呼び出すまで保持されます。

C++11 準拠のコンパイラでは、オプション 4 も機能するはずです。これは、閉じて再度開くと以前の状態がクリアされるためです。古いコンパイラはそうしないかもしれません。

于 2013-04-05T07:27:09.407 に答える
1

試す:

inStream.seekg(0, ios_base::beg);
于 2013-04-05T07:24:59.203 に答える