c++pointersnewlinefile-structure

How to get the file pointer to the next line in c++?


Given below is a part of my whole program:

         void filewrite(fstream &f2)
         {
            f2.seekp(0,ios::beg);
            f2.write(customerno,strlen(customerno));
            f2.seekp(24,ios::beg);
            f2.write(customername,strlen(customername));
            f2.seekp(56,ios::beg);
            f2.write(product,strlen(product));
            f2<<endl;
         }

here f2 is the file pointer customerno,customername and product are strings 0,24 and 56 are respective positions for these strings from the beginning

the problem i m facing is, everytime i m trying to write a new record it is over writing the previous one and not going to the next line.

i want each new record to be aligned with 0th, 24th and 56th position. how should i do this ? Thanks in advance.


Solution

  • You are giving yourself a challenging problem if you use that method. You want to use std::setw() to do this for you.

    Here is a far simpler method to do this:

    #include <fstream>
    #include <iomanip>
    using namespace std; 
    void filewrite(ofstream &f, string customerno, string customername, string product)
    {
       f << left << setw(24) << customerno << setw(32) << customername << product << endl;
    }