0

私は自分のクラスのプロジェクトに取り組んでいます。そして、一部を除いてすべてが機能するようになりました。ファイルから整数を読み込んで、それらを bankQueue と eventList に変換しています。これを一度に1行ずつ行う必要があります。

私のファイルは次のようになります。

1 5
2 5
4 5
20 5
22 5
24 5
26 5
28 5
30 5
88 3


// Get the first arrival event from the input file, and place it in eventList
tempArrivalEvent.type = ARRIVAL;
inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength;
eventList.insert(tempArrivalEvent);

これは、データの最初の行を 2 つの変数に格納するように機能する私の最初のコードです。私が抱えている問題は、後で次の行を追加するときです。次のコードは、上記のコードとは別の関数にあります。

if (!inFile.eof())
{
    tempArrivalEvent.type = ARRIVAL;
    inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength;
anEventList.insert(tempArrivalEvent);
} // end if

2 番目のコードは、最初のコードとまったく同じ行のデータを取得します。次の行にジャンプする必要がありますが、わかりません。これが私のプロジェクトの動作を妨げる唯一のものです。

4

1 に答える 1

1

何よりもまず、2 つのフォーマットされた入力の実際の読み取り抽出の潜在的な失敗を完全に無視しています。抽出の結果として istream の状態を調べるだけで、非常に簡単に検証できます。最初のケースは次のようになります。

tempArrivalEvent.type = ARRIVAL;
if (inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength)
    eventList.insert(tempArrivalEvent);

次に、提示されたコードに関連している可能性が高いので、これを検討してください。そこに到着したら、EOFを超えて読み取ろうとするまで表示されinFile.eof()ません(それまですべてが成功していると仮定します)。したがって、このコードも正しくありません。true

if (!inFile.eof())  // nope, not set yet
{
    tempArrivalEvent.type = ARRIVAL;

    // both of these fail since we're at EOF, which will now be reported
    //  as such after the first failure. We, however, never check the stream
    //  status, and thus blindly insert whatever junk happened to be in the
    //  tempArrivalEvent object, likely data from a prior insert.
    inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength;

    // insert unvalidated data
    anEventList.insert(tempArrivalEvent);
} // end if

これは...最初の read とまったく同じはずです。抽出が成功したことを確認してから、イベント リストの挿入を実行します。

tempArrivalEvent.type = ARRIVAL;
if (inFile >> tempArrivalEvent.beginTime >> tempArrivalEvent.transactionLength)
    anEventList.insert(tempArrivalEvent);

注:これはすべて、両方の抽出コード スライスで同じオブジェクトであることを前提inFileとしています。 ifstreaminFile別の関数で最初のケースを参照によって2番目のケースに渡しているかどうかを明確にしていません。連続した読み取りを正しく機能させたい場合は、参照渡しする必要があります(または、震え、グローバルを使用します)。

于 2013-04-02T06:01:47.457 に答える