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;