-3

我想在 c++ 中从具有常规 int 的结构中添加一个 int。有没有简单的方法来做到这一点?我几乎在所有地方都进行了搜索,但是在从二进制文件中读取数据时添加两个 struct int 或将常规 int 和 struct int 一起添加没有任何内容。

这是我目前拥有的简单版本。

 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.    

问题是,当我输出总计时,它只给了我尝试添加 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 回答