Code:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int get_int(int default_value);
int main(int argc, char *argv[])
{
char filename[MAX_PATH + 1];
int n = 0;
char model[20];
char make[20];
char year[5];
int mileage;
int recsize = sizeof(model) + sizeof(make) + sizeof(year) + sizeof(int);
cout << "Enter file name: ";
cin.getline(filename, MAX_PATH);
fstream fbin(filename, ios::binary | ios::out);
if (!fbin)
{
cout << "Could not open" << filename << endl;
system("PAUSE");
return -1;
}
cout << "Enter file record number: ";
n = get_int(0);
cout << "Enter model: ";
cin.getline(model, sizeof(model) -1);
cout << "Enter make: ";
cin.getline(make, sizeof(make) -1);
cout << "Enter year: ";
cin.getline(year, sizeof(year) -1);
cout << "Enter mileage: ";
mileage = get_int(0);
cout << "your current mileage is " << mileage;
fbin.seekp(n * recsize);
fbin.write(model, sizeof(model) -1);
fbin.write(make, sizeof(make) -1);
fbin.write(year, sizeof(year) -1);
fbin.write((char*)(&mileage), sizeof(int));
fbin.close();
system("PAUSE");
return EXIT_SUCCESS;
}
#define COL_WIDTH 80
int get_int(int default_value)
{
char s[COL_WIDTH + 1];
cin.getline(s, COL_WIDTH);
if(strlen(s) == 0)
return default_value;
return atoi(s);
}
(please note this is Exercise 8.3.1 from the book Without Fear by Brian Overland)
Essentially this is just supposed to create a record by asking the User to input the file to write into or create and write into, the record number to write on, the model, make, year, and mileage.
After that it will write the data into the new file in binary - then exit.
Problem I get is when I compile and run the program it works fine until it gets to the mileage part. It prompts the user to enter the mileage but immediately skips the cin.getline() located in the get_int(). The results for mileage always come out as the default_value. Not sure what is happening here.