STL List
Mar 7, 2010 at 9:28pm UTC
Hi all,
I need help manipulating an STL List, I need to be able to populate the list with values that I read in from a .txt file. I need to do this with a For loop, incrementing the position each time. I can't figure out how to do this, here is my loop thus far:
1 2 3 4 5 6 7 8
for (i2=1; !iFile.eof(); i2++)
{
iFile >> coefficient >> exponent;
polynomial1.insert(i2, atoi(coefficient.c_str()));
polynomial1.insert(i2 ,atoi(exponent.c_str()));
}
any help would be appreciated, let me know if you need to see anymore of my code.
Thanks in advance.
Mar 7, 2010 at 10:09pm UTC
you don't need to keep track of a position for this. just push_back to the end of the list:
1 2 3 4
while (!iFile.eof())
{
polynomial1.push_back( /*whatever*/ );
}
Mar 8, 2010 at 1:47am UTC
thanks for your help...but now I'm stuck again...I need for the output file to read exactly as the input file does but as you can see I'm printing an extra value as well as printing two values in reverse order...it has to be something with my loop but I cant figure it out
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
int main(int argc, char *argv[])
{
ifstream iFile;
ofstream oFile;
list<int > polynomial;
list<int > polynomial1;
if (argc != 3)
{
cerr << "Command requires <input_file> <output_file>" << endl;
return EXIT_FAILURE;
}
else
{
// open files
iFile.open(argv[1]);
oFile.open(argv[2]);
if ( iFile.is_open() && oFile.is_open() )
{
string coefficient;
string exponent;
while (!iFile.eof())
{
iFile >> coefficient >> exponent;
oFile << coefficient << " " << exponent << endl;
if (coefficient == "XXX" )
{
coefficient = exponent;
iFile >> coefficient;
polynomial.push_back(atoi(coefficient.c_str()));
polynomial.push_back(atoi(exponent.c_str()));
oFile << coefficient << " " << exponent << endl;
while (!iFile.eof())
{
iFile >> coefficient >> exponent;
polynomial1.push_back(atoi(coefficient.c_str()));
polynomial1.push_back(atoi(exponent.c_str()));
oFile << coefficient << " " << exponent << endl;
}
}
}
}
// close files
iFile.close();
oFile.close();
return EXIT_SUCCESS;
}
}
input.txt
output.txt
Topic archived. No new replies allowed.