我想在c ++中使用常规int从结构中添加一个int。有一个简单的方法吗?我几乎到处搜索,但是在从二进制文件读取数据或者将常规int和struct 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;
答案 0 :(得分: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;
}