In article <11**********************@m7g2000cwm.googlegroups. com>,
ck*******@gmail.com says...
I have the following two files:
File1:
11 John Doe
33 Jane Doe
55 Steve Smith
File2:
22 Joe Doe
44 Willy Widget
I'm trying to merge the two files to look like:
Output:
11 John Doe
22 Joe doe
33 Jane Doe
44 Willy Widget
55 Steve Smith
I'd define a class that holds the data and defines operator< to sort the
data in the desired fashion (you haven't described what should happen
if, for example, the same number appears with two different names).
From there, you can directly merge from input files to an output file if
the input files are guaranteed to be sorted, as you've shown them here.
Otherwise, you can copy from the input files to a sorted container (e.g.
set or multiset, depending on whether duplicate keys are allowed) and
then merge from there to the output.
I'm not sure why can _can't_ use arrays (as you mentioned in a snipped
portion of your post) but I'd certainly consider it ill-advised.
As far as the code you have goes, something like this:
while (!File2.eof())
{
File1 >File1_num >File1_FirstName >File1_LastName;
is essentially certain to be incorrect, and normally needs to be
rewritten to something like:
while (file1>>input1>>input2>>input3>>inputN)
// whatever
The important point is that you need to check for a problem with reading
the input file AS you read it -- file.eof() only becomes true AFTER
you've reached the end of the file, so your loop attempts to read the
last data in the file twice. I'd forget about using explicit loops,
however, and just use an std::istream_iterator to read the input.
Your code also has a problem in that each iteration through the loop
reads input from each file, but only writes an output from one file --
and discards the input it read from the other file. Each iteration
should read only ONE input, to replace the one just written out.
As previously noted, however, I'd use std::merge() for this job -- it's
written specifically for tasks like this, and does them quite nicely.
class record {
int number;
std::string first_name, last_name;
public:
friend
std::istream &operator>>(std::istream &in, record &r) {
return in >r.number >r.first_name >r.last_name;
}
friend std::ostream &operator<<(std::ostream &os, record const &r) {
return os << r.number << "\t"
<< r.first_name << "\t"
<< r.last_name;
}
bool operator<(record const &other) const {
return number < other.number;
}
};
// ...
std::merge(
std::istream_iterator<record>(infile1),
std::istream_iterator<record>(),
std::istream_iterator<record>(infile2),
std::istream_iterator<record>(),
std::ostream_iterator<record>(outfile, "\n"));
--
Later,
Jerry.
The universe is a figment of its own imagination.