Hello,

I am attempting to take user input and write it to a file in the form
of a record. I am having some difficulty in getting an integer and
writing it to the file. I am not sure if I am receiving it in the
wrong manner, or if I am writing it to the file in a wrong manner.
Where the integer should be I get non-numbers (sometimes very strange
ones). Can some please tell me what I am doing wrong? Any help would
be greatly appreciated!

nim.

#include <iostream>
#include <fstream>
#include <string.h>  
using namespace std;

int get_int(int default_value);
char name[21];

int main() {
   char filename[81];  //receives the filespec of the file
   int mileage;
   int n; //receives the record number for file write
   int recsize = sizeof(name) + sizeof(int);  //set the record size

   cout << "Enter a filename: ";
   cin.getline(filename, 80);
   
   //open file for binary read/write access
   fstream myFile(filename, ios::binary | ios::in | ios::out);
   if(!myFile){                  
      cout << "Could not open the file " << filename;
          return -1;
        }
        
   //get record number and go to record
   cout << "Enter a record number and press Enter: ";
   n = get_int(0);  
   
   //get input from user
   cout << "Enter model: ";
   cin.getline(name, 20);
   cout << "Enter mileage: ";
   mileage = get_int(0);
   
   //write data to file   
   myFile.seekp(n * recsize);  
   myFile.write(name, 20); //name var is type char, so no type
conversion necessary
   myFile.write(reinterpret_cast<char*>(&mileage), sizeof(int));      

   myFile.close();  
   return 0;
  }

  //get integer function.
  int get_int(int default_value) {
     char s[81];
         
         cin.getline(s,80);
         if (strlen(s) == 0) {
            return default_value;
                }
            return atoi(s);
  }
  


Reply via email to