-3

C++の通常のintで構造体からintを追加したいと思います。それを行う簡単な方法はありますか?私はほとんどどこでも検索しましたが、バイナリファイルからデータを読み取るときに2つのstruct intを追加したり、通常のintとstructintを一緒に追加したりすることには何の意味もありません。

これは私が現在持っているものの単純なバージョンです。

 struct Add{
    int k;
    };

    int total;

    Add a;

//read in first set of number from binary file
    total += a.k; 
//add up to total, then read in second set of number from binary file.    

問題は、totalを出力すると、int kを追加しようとした最後の数値のみが表示され、合計は表示されないことです。

要求された私の実際のコード。

struct TaskInit{
    int weight;
};

TaskInit t;

    int totalWeight;

    for (int i = 1; i <= noOfRecords; ++i)
    {
        afile.seekg ((i - 1) * sizeof (TaskInit), ios::beg);
        afile.read (reinterpret_cast <char *>(&t), sizeof (t));

         totalWeight +=  t.weight;

    }
   cout << totalWeight;
4

1 に答える 1

1
struct Add{
    int k;
    };

    int total = 0; // no indeterminate values. always init locals!

    Add a;
   // open your file here. 
  while (inFile >> a.k) {

//read in first set of number from binary file
//add up to total, then read in second set of number from binary file.
      total += a.k;
  }
于 2013-01-14T11:34:50.237 に答える