![]() |
[C++] Help finishing code..STUCK
Hi, I have this program it goes through 2 input files then outputs their contents into another file and the outputs are saposta be sorted in alphabetical order. The probelm is one file is shorter than the other and as my program is now it sorts just fine untill it hits the eof of one of the files before the other then its messed up. Heres my code so far
Quote:
|
your problem looks to be here
inFile.getline(input1, 101); inFile2.getline(input2, 101); } itll try getting a newline even tho eof has been reached replace it like this if infile.eof=false then getline else print all of infile2 and quit similarly for infile2 |
The output wont be alphabetical. You may want to read everything into a container class, sort it, and then write the output file.
C++ container classes should have sort functions built in, so that step becomes 1 line. For example, infile1= aa ab ac infile2= bb bc bd Your output, I believe, would be aa bb ab bc ac bd Since you only compare adjacent lines. |
Here is a link to an introduction to the C++ STL (standard template library)
http://www.topcoder.com/index?t=features&c=feat_082803 |
What you'll probably want to use is merge-sort to organize the data. I believe the STL has containers to help with merge-sort.
|
Yeah, you'll have to read all of the data in, then sort it. At the moment, you're just comparing adjacent lines like BAMF said.
As a general note, you'll want to be checking EOF before you start reading lines, to stop it going off the end. Quote:
while(!inFile.eof() || !inFile2.eof()) { inFile.getline(input1, 101); inFile2.getline(input2, 101); ... } or something. |
You also have a potential buffer overflow by passing 101 as the buffer size parameter to istream::getline, which should be 100, the size of your buffers. Also, if you use code tags instead of quote tags you can include the whitespace so reading the code isn't painful.
This is almost ridiculously easy if you use STL strings and vectors as you can sort everything with one statement eg: Code:
string s; |
Call me a java fanboi, but thats ^^^ why I HATE C++.
|
You Java fanboy! C++ forever! (Though to be honest, I'm not a huge fan of C++ - I'm a C/Perl man myself).
|
All times are GMT -8. The time now is 03:25 PM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project