Ahh yes where's my manners. Code, yes:
Code:
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
char model[20];
char make[20];
int get_int(int default_value){
char s[81];
cin.getline(s, 80);
if (strlen(s) == 0)
return default_value;
return atoi(s);
}
int main()
{
char filename[81];
int mileage;
int recsize = sizeof(int) + sizeof(model) + sizeof(make) + sizeof(int);
int recnumber;
int year;
//Filename
cout << "Enter a filename: ";
cin.getline(filename, 80);
//Open File for binary read and write
fstream fbin(filename, ios::binary | ios::in | ios::out);
if (!fbin) {
cout << "Error. File Could Not Be Opened!" << endl;
return -1;
}
//Record Number
cout << "Enter File Record Number: ";
cin >> recnumber;
cin.ignore(100, '\n');
//Record User Input.
cout << "What is the model? ";
cin.getline(model, 19);
cout << "What is the make? ";
cin.getline(make, 19);
cout << "What is the year? ";
year = get_int(0);
cout << "What is the mileage? ";
mileage = get_int(0);
fbin.seekp(recnumber * recsize);
fbin.write(model, 20);
fbin.write(make, 20);
fbin.write(reinterpret_cast<char*>(&year), sizeof(int));
fbin.write(reinterpret_cast<char*>(&mileage), sizeof(int));
fbin.close();
_getch();
}
I've had to replace those in Red With
Code:
char Year[5]
...
cin.getline(Year, 4)
^^If I used those instead of the red bolded things on the code. My Following Output Would Occur.
Code:
Enter A Filename: (I inserted File Name, Not Important)
Enter File Record Number 2:
What is the model? 2600GTS (Making It Up)
What is the make? Ford
What is the year? 1900
What is the mileage? (AFTER I PRESS A NUMBER, PROGRAM CLOSES)
I think this is due to when inputting 1900, it went to mileage aswell. I think this is like a case of user inputting a string, and then pressing enter, then a user should input another string for another variable, but it assumed enter was it. That's why cin.ignore was used for that. However it is different for here.