| | |
Setting an array and reading in a txt file backwards
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Apr 2007
Posts: 4
Reputation:
Solved Threads: 0
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.
c Syntax (Toggle Plain Text)
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(); }
Last edited by WaltP; Apr 5th, 2007 at 2:46 pm. Reason: Added CODE tags -- read the words you typed over input text box...
•
•
Join Date: Jul 2005
Posts: 1,671
Reputation:
Solved Threads: 261
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
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
Last edited by Lerner; Apr 5th, 2007 at 1:27 pm.
•
•
Join Date: Dec 2006
Posts: 1,089
Reputation:
Solved Threads: 164
a. read the lines and insert it into a vector
b. iterate over the vector backwards to
access the redords in reverse order
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
C++ Syntax (Toggle Plain Text)
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
C++ Syntax (Toggle Plain Text)
ofstream outfile("custFileCopy.txt") ; std::copy( records.rbegin(), records.rend(), std::ostream_iterator<string>(outfile) );
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
Last edited by vijayan121; Apr 5th, 2007 at 1:37 pm. Reason: correct syntax error
•
•
Join Date: Apr 2007
Posts: 4
Reputation:
Solved Threads: 0
•
•
•
•
a. read the lines and insert it into a vector
C++ Syntax (Toggle Plain Text)
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
you can do this only if the file is small enough;C++ Syntax (Toggle Plain Text)
ofstream outfile("custFileCopy.txt") ; std::copy( records.rbegin(), records.rend(), std::ostream_iterator<string>(outfile) );
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:
C++ Syntax (Toggle Plain Text)
{ 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; }
•
•
Join Date: Dec 2006
Posts: 1,089
Reputation:
Solved Threads: 164
to fix the compiler error:
u need to declare the function before u
call it. add the following anywhere before
the call.
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
were u not trying to read strings (lines)
from the file (not integers) in the original
post?
u need to declare the function before u
call it. add the following anywhere before
the call.
C++ Syntax (Toggle Plain Text)
void backward(vector <int> vect) ;
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
C++ Syntax (Toggle Plain Text)
void backward( const vector<int>& vect ) ;
were u not trying to read strings (lines)
from the file (not integers) in the original
post?
•
•
Join Date: Apr 2007
Posts: 4
Reputation:
Solved Threads: 0
•
•
•
•
to fix the compiler error:
u need to declare the function before u
call it. add the following anywhere before
the call.
a vector is really a dynamically resizeableC++ Syntax (Toggle Plain Text)
void backward(vector <int> vect) ;
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
C++ Syntax (Toggle Plain Text)
void backward( const vector<int>& vect ) ;
were u not trying to read strings (lines)
from the file (not integers) in the original
post?
•
•
Join Date: Dec 2006
Posts: 1,089
Reputation:
Solved Threads: 164
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.
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.
Last edited by vijayan121; Apr 5th, 2007 at 4:21 pm. Reason: spelling
•
•
Join Date: Jul 2005
Posts: 1,671
Reputation:
Solved Threads: 261
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.
C++ Syntax (Toggle Plain Text)
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
•
•
Join Date: Dec 2006
Posts: 1,089
Reputation:
Solved Threads: 164
•
•
•
•
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.
C++ Syntax (Toggle Plain Text)
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
well, i suppose everyone has a right to their opinion.
Last edited by vijayan121; Apr 6th, 2007 at 1:19 am. Reason: correct typo
![]() |
| Thread Tools | Search this Thread |
api array based beginner binary bitmap c++ c/c++ calculator char char* class code coding compile compiler console conversion count database delete deploy desktop developer dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker list loop looping loops map math memory multiple news node number numbertoword output parameter pointer problem program programming project python random read recursion recursive reference rpg sorting string strings struct temperature template test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






