将包含数组的结构写入二进制文件

时间:2016-04-27 15:51:58

标签: c++

我提示用户输入销售数据,然后将该数据添加到struct数组中。这是怎么回事呢?

这是我的结构:

struct CompanyDivision {
char name[NAME_LENGTH];
double quarterlySales[QUARTERS];};

这是我的主要

int main() {

const int DIVISIONS = 4;


CompanyDivision allDivisions[DIVISIONS] = {{ "North" }, { "South" }, { "East" }, { "West" }};

cout << "Please enter the sales figures for each quarter at each division: " << endl;

for (int quarter = 0; quarter < QUARTERS; quarter++) {
    cout << "\n**For quarter " << quarter + 1 << endl;
    for (int division = 0; division < DIVISIONS; division++) {
        cout << "\t" << allDivisions[division].name << " >> $";
        cin >> allDivisions[division].quarterlySales[quarter];
        while (allDivisions[division].quarterlySales[quarter] < -1) {
            cout << "Please enter a non-negative sales figure." << endl;
            cout << "\t" << allDivisions[division].name << " >> $";
            cin >> allDivisions[division].quarterlySales[quarter];
        }
    }
    cout << endl;
}
ofstream outputFile("QuarterlySales.dat", ios::binary | ios::out);
for (int i = 0; i < QUARTERS; i++) {
    for (int j = 0; j < DIVISIONS; j++) {
        outputFile.write(reinterpret_cast <char*> (&allDivisions[i].quarterlySales[j]), sizeof(CompanyDivision)* 4);
    }
}
outputFile.close();

system("pause");
return 0;

}

嵌套for循环是否正确完成每个分区(北,南,西,东)和那些四分之一(1,2,3,4)以及写出二进制文件的语法是否正确?

谢谢!

1 个答案:

答案 0 :(得分:0)

for表达式是正确的......这就是全部!

  • 您正在将'\n'std::endl混合到输出行的末尾:在C ++中坚持以前
  • 您从cin读取了双倍值而没有测试读数是否正确:阅读后使用if (!cin) {...}
  • 非负面测试(否定)应为<= -1或更好< 0
  • outputFile.write(reinterpret_cast <char*> (&allDivisions[i].quarterlySales[j]),对于第一部分是正确的(将指针转换为double char *是有效的),但大小应为sizeof(double)sizeof(allDivisions[i].quarterlySales[j])或{{ 1}}

但是你应该记住,将二进制值存储到文件中是不可跨越不同架构的。