I have been having difficulty trying to figure out how to read in data backwards. I get the idea, but have no idea how to properly code it since it is string data from a txt file. I was given the basic file to start with, but need to add in an array that will not assume more than 100 records.

void  main()
{
  fstream custFile, custFileCopy;
  string custRecord;
     
   custFile.open("customer.txt", ios::in);   
   if(custFile.fail())
   { cout << "Master input file can't be opened. Program stopping." << endl;
     return;
   }
  
  custFileCopy.open("custFileCopy.txt", ios::out); 
   if(custFileCopy.fail())
   { cout << "Input file can't be opened. Program stopping." << endl;
     return;
   } 
  
   getline(custFile, custRecord);
   
   char c;
  
    while (!custFile.fail() )
    {   int i = 0;
        while(!custRecord[i] == 0)
        {   c = custRecord[i];
            cout << c;
          i++;
        }
   
     cout << endl;
          
     custFileCopy << custRecord << endl;// write an output record 
     getline(custFile, custRecord); // read another input record
            
   } 
      custFile.close(); 
      custFileCopy.close();
}

Recommended Answers

All 10 Replies

Welcome to Daniweb C/C++.

Please read the announcement at the top of the page regarding use of BB tags or the watermark in the Message box regarding the use of code tags specifically. Using these tags will keep the formatting of your code as you post it. If you don't indent, etc, please do.

For your particular problem I recommend you write out the steps first, then try to write code. Here's a sample of how you might do it

//I'll need
a file to read from
a second file to write to
an array to hold all the strings I read from file 1 and will write to file 2

//order of program
open file 1
check file 1 is open

open file 2
check file 2 is open

use a loop to read each string from file 1 one by one
place each string into the array as it's read
keep track of how many strings have been read in

use a loop to write the array of strings to file 2 starting from the last string read in to the first string read in

close both files

a. read the lines and insert it into a vector

ifstream file("customer.txt") ;
string rec ;
vector<string> records ;
while( getline(file,rec) ) 
    records.push_back(rec) ;

b. iterate over the vector backwards to
access the redords in reverse order

ofstream outfile("custFileCopy.txt") ;
  std::copy( records.rbegin(), records.rend(),
        std::ostream_iterator<string>(outfile) );

you can do this only if the file is small enough;
for very large files memory may not be sufficient.
u could however read the file in parts (say 1000 records),
create intermediate output files (as above) and then
merge them in reverse order of creation.

*** note: i had not seen Lerner's post; it came in while i was
typing in the reply. so this is just a repetition of what was
suggested in that post

a. read the lines and insert it into a vector

ifstream file("customer.txt") ;
string rec ;
vector<string> records ;
while( getline(file,rec) ) 
    records.push_back(rec) ;

b. iterate over the vector backwards to
access the redords in reverse order

ofstream outfile("custFileCopy.txt") ;
  std::copy( records.rbegin(), records.rend(),
        std::ostream_iterator<string>(outfile) );

you can do this only if the file is small enough;
for very large files memory may not be sufficient.
u could however read the file in parts (say 1000 records),
create intermediate output files (as above) and then
merge them in reverse order of creation.

*** note: i had not seen Lerner's post; it came in while i was
typing in the reply. so this is just a repetition of what was
suggested in that post

*******************
Thanks for your help. I am quite the newbie to this board! I am figuring out the in's and out's quickly though!

I started looking into the vector and think that is a much easier route. Here is what I came up with, however my compiler is still giving me two errors. It does not recognize my "backward" identifier from the function. Any suggestions on how to make the function work correctly?

I inserted this after reading from file:

{
        const int records = 200;
    vector<int> customer(records);
    string rec;

    for (int count = 0; count < records; count++)
        customer.push_back(count--);
    backward(customer);
    }

// Closing the files
    cout << "\n\n\nClosing files.\n\n\n";
    custFile.close();
    custFileCopy.close();
    cout << "Program has ended.\n\n\n";
}

void backward(vector <int> vect)
{
    for (int count = 0; count < 200; count++)
        cout << vect[count] << " ";
    cout << endl;
}

to fix the compiler error:
u need to declare the function before u
call it. add the following anywhere before
the call.

void backward(vector <int> vect) ;

a vector is really a dynamically resizeable
array; paasing it by value is not a good
idea at all.
(u are copying a large collection!)
in general, for any user defined type,
prefer passing by const referance instead
of by value. so i would also suggest u
change the signature of backward to

void backward( const vector<int>& vect ) ;

were u not trying to read strings (lines)
from the file (not integers) in the original
post?

to fix the compiler error:
u need to declare the function before u
call it. add the following anywhere before
the call.

void backward(vector <int> vect) ;

a vector is really a dynamically resizeable
array; paasing it by value is not a good
idea at all.
(u are copying a large collection!)
in general, for any user defined type,
prefer passing by const referance instead
of by value. so i would also suggest u
change the signature of backward to

void backward( const vector<int>& vect ) ;

were u not trying to read strings (lines)
from the file (not integers) in the original
post?

Ok, that did fix the compiler error. Yes I am trying to read in complete lines from a txt file, which includes for example customer names and addresses. But I had to declare a maximum of 100 to 200 records total. Now I just need to read in each line instead of all 0's. That was my error in trying to do this too quickly!

u need to use a vector<string>, not
vector<int>.

and u need to use getline to read in
eah line till eof. the file is read from
begin to end (forward). after inserting
the lines into the vector, iterate
backwards in the vector (from the
last element to the first).

do not worry about the number of
lines (as long as it is not impossibly
large); when u call push_back the
vector resizes itself. start with an
empty vector; after adding all the lines
(push_back), the size() method of the
vector will tell u how many strings have
been added. this is useful if u want to
iterate over it like a c style array; start
with pos size()-1 and end at pos zero
to iterate backwards.

IMO, sometime STL classes are more hassle than they are worth. One such occassion is during a class when the instructions are to use an array. Another is when the upper bounds of the array are given. And another is when the user has no idea what a template or an iterator is.

ifstream fin("inputFile.txt"); //to read from file
ofstream fout("outputFile.txt"); //to write back to file 
string input[100]; //to hold input
int i = 0;  //to keep track of how many strings actually read in, may be less than max possible.

//validate files are open here

//read input file one string at a time, adding it to the array in the appropriate index
while(getline(fin, input[i]))
   i++;

//write to output file (frontwards for this demonstration) one string per line
for(int x  = 0; x < i; ++x)
      fout << input[i] << endl;

//close files here

IMO, sometime STL classes are more hassle than they are worth. One such occassion is during a class when the instructions are to use an array. Another is when the upper bounds of the array are given. And another is when the user has no idea what a template or an iterator is.

ifstream fin("inputFile.txt"); //to read from file
ofstream fout("outputFile.txt"); //to write back to file 
string input[100]; //to hold input
int i = 0;  //to keep track of how many strings actually read in, may be less than max possible.
 
//validate files are open here
 
//read input file one string at a time, adding it to the array in the appropriate index
while(getline(fin, input[i]))
   i++;
 
//write to output file (frontwards for this demonstration) one string per line
for(int x  = 0; x < i; ++x)
      fout << input[i] << endl;
 
//close files here

prefer an array to a vector to bring the all the lines of a text file into memory?
well, i suppose everyone has a right to their opinion.

u ... u ... u ... u ...

:confused:
Read this please.

I almost have this running. I finally figured out how to get the array working! Woohoo. Its interesting to see how it can be worked different ways. Thanks for all of your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.