Binary file I/O

I'm learning how to write data to binary file and how to read it.
Here's a program. when I run it and choose option to display all departments it displays two departmnts at once and then waits for the user input to display next department.


#include<iostream>
#include<string>
#include<cstring>
#include<fstream>
using namespace std;


const int max_char = 40;

struct Department
{
int depID;
};

void startProgram(Department dep);
void createDepartment(Department dep);
void displayAllDepartments(Department dep);

int main()
{
Department dep;
startProgram(dep);
}

void startProgram(Department dep)
{
int choice;
cout << "Menu: ";
cout << "\n1. Create Department";
cout << "\n2. Display all departments" << endl;
cin >> choice;

switch (choice)
{
case 1:
system("cls");
createDepartment(dep);

system("cls");
startProgram(dep);
case 2:
system("cls");
displayAllDepartments(dep);

system("cls");
startProgram(dep);
}
}

void createDepartment(Department dep)
{
string temp;
int depID;

cout << "Creating department" << endl;

ofstream departments;
departments.open("dep.dat", ios::out | ios::app | ios::binary);
if (!departments)
{
cout << "Error opening file.";
}

cout << " Please enter department ID: ";
cin >> dep.depID;

departments.write((char *)(&dep), sizeof(dep));
departments.close();
}

void displayAllDepartments(Department dep)
{
ifstream departments;
departments.open("dep.dat", ios::in | ios:: binary);

departments.read((char*)&dep, sizeof(dep));
while (!departments.eof())
{
cout << "\nDepartment ID: " << dep.depID;
cout << "\nPress any key to display next department." << endl;
cin.get();
departments.read((char*)&dep, sizeof(dep));
}
departments.close();
cin.get();
}
The reason is that an the operator >> (e.g. cin >> choice;) leaves a whitespace/end of line in the stream. cin.get(); will retrieve that remaining whitespace and does not wait for user input. You can avoid this when you put ws after the operator >>:

cin >> choice >> ws;

See:
http://www.cplusplus.com/reference/istream/ws/?kw=ws
It doesn't seem working.

When I change cin >> choice; to cin >> choice >> ws; the program doesn't go to switch.
Topic archived. No new replies allowed.