-
December 29th, 2003, 04:57 PM
#1
Uploading Vector To File
I am now using Dev-C++ 4, and am trying to upload my vector elements using the infile as I did with VC4, but I do realize that they are not the same.
Code:
#include <fstream>
#include <vector>
#include <string>
#include <stdlib.h>
int main()
{
// dcelare variables
ifstream infile;
std::vector <string> username;
username.reserve(100);
short index;
// get usernames from file
infile.open("user_db.dat", ios::in);
index = username.size();
do
{
index--;
infile >> username[index];
}
while(index != 0);
infile.close();
system("PAUSE");
return 0;
}
It compiles right, but I get an error when running it saying it has performed an illegal operation and closes. Any help?
JDM
-
December 29th, 2003, 05:45 PM
#2
Re: Uploading Vector To File
Originally posted by lifeofjdm
I am now using Dev-C++ 4, and am trying to upload my vector elements using the infile as I did with VC4, but I do realize that they are not the same.
Code:
username.reserve(100);
//....
infile >> username[index]; // illegal operation
The vector is empty, and you are trying to access a non-existing element. You are lucky it doesn't crash in VC 4.0.
No, reserve() does not add elements to the vector, resize() does.
The reserve function only gives the vector more memory up front so that operations such as push_back() are more efficient. The reserve() does not actually give you more elements.
Code:
username.resize(100);
//....
infile >> username[index]; // OK if index is between 0 and 99, inclusive
Regards,
Paul McKenzie
-
December 29th, 2003, 06:46 PM
#3
Thank you very much! ...
JDM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|