3

I have a file with 10 integers. I read the file and put it into a list. I then modify the list (add, delete, etc) and now I want to be able to save that list. So I have no idea how to take the items from my array list and save it into the file.

1) Read the file and put it into list:

ifstream intFile, floatFile;
ofstream intFileOut, floatFileOut;

SortedList<int> intList;
SortedList<float> floatList;
int a=0;
float b=0;

intFile.open("int.dat");                            
floatFile.open("float.dat");    

while(intFile>>a)
{
    intList.InsertItem(a);
    a++;
}

while(floatFile >>b)
{
    floatList.InsertItem(b);
    b++;
}

intFile.close();    
floatFile.close();

2) Modified the list

cout<<"------------------------------"<<endl;
cout<<"INT LIST: "<<endl;
cout<<"Adding 1 to list..."<<endl;
intList.InsertItem(1);
cout<<"Adding 2 to list..."<<endl;
intList.InsertItem(2);
cout<<"Deleting int 20 from the list..."<<endl;
intList.DeleteItem(20);
cout<<"------------------------------"<<endl;
cout<<"INTs in the list: "<<endl;
intList.GetNextItem(a);
cout<<"------------------------------"<<endl;
cout<<"Retriving int 30..."<<endl;
cout<<"Position of int 30: ";intList.RetrieveItem(30);cout<<endl;

3) Now I want to take the intList and save it to intFileOut, if that makes sense?

Any tips/help would be appreciated.

4
  • Btw, according to MSDN, SortedList either takes 2 template parameters (System.Collections.Generic) or none at all (System.Collections). Commented Nov 13, 2011 at 21:22
  • Also I would use fstream (read & write) instead of separate ifstream and ofstream objects. Commented Nov 13, 2011 at 21:24
  • Also a++ and b++ seems unnecessary. Commented Nov 13, 2011 at 21:30
  • ifstream and ofstream is the way the teacher wanted us to do it and im still getting used to reading and writing file. I just made another file to save the file. It works perfectly and thanks for the suggestion for fstream. I will look into it more. Commented Nov 13, 2011 at 21:31

1 Answer 1

2

Does this work for you?
(I don't have visual C++ installed nor am I familiar with its special quirks)

for (int i = 0; i < intList.Count; i++)
{
    intFileOut << intList.GetByIndex(i) << endl;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I used something similar to your suggestion but just made a saveFile function and it works the same way. Just outputs all of the items into the new file I created. Thank you for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.