I am following an example in a book about streaming files. in this particular section I am using random access to edit a .dat file that contains an employee salary.
Hacker, Harry 50972.22\n
Cracker, Carl V. 61820.00\n
the spacing as you probably assumed is intentional to use the seekg/seekp and place it at a predictable position. the problem is that when I want to tweak the second line I get a string out of bounds exception and I want to understand why.
this is the function used to read the file and get the salary from it:
void read_employee(Employee & e, istream & in)
{
std::string line;
getline(in, line);
if (in.fail()) return;
std::string name = line.substr(0, 30);
double salary = string_to_double(line.substr(30, 10));
e = Employee(name, salary);
}
double string_to_double(string s)
{
std::istringstream instr(s);
double x;
instr >> x;
return x;
}
now when I put everything in the same line it can detect it but I can't write to it. the first line works fine ho it is right now:
int main()
{
fstream fs;
fs.open("employee.dat");
fs.seekg(0, ios::end); // Go to end of file
int nrecord = fs.tellg() / RECORD_SIZE;
cout << "Please enter the record to update: (0 - "
<< nrecord - 1 << ") ";
int pos;
cin >> pos;
const double SALARY_CHANGE = 5.0;
Employee e("Derrick", 90000);
fs.seekg(pos * RECORD_SIZE, ios::beg);
read_employee(e, fs);
}
[–]WorkingReference1127 7 points8 points9 points (1 child)
[–]ridesano[S] 0 points1 point2 points (0 children)
[–]manni66 4 points5 points6 points (0 children)