By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,640 Members | 1,581 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,640 IT Pros & Developers. It's quick & easy.

Trying to insert into vector<struct_type> results in "Access Violation" Error...

P: 13
Hi,

I want to read data from a txt-file that looks like this:

aaa 4 12.45
bbb 3 7.34
ccc 12 3.45

and store the data in an array of structures. The struct and array are defined like this

Expand|Select|Wrap|Line Numbers
  1. struct proPkaData {
  2.         char Name[4];
  3.         int Index;
  4.         float Pka;
  5.         } Data;
  6.  
  7. vector<proPkaData> DataArray;
The main program looks something like this:

int i=0;
while (!infile.eof()){
infile>>DataArray[i].Name;
i++

The program compiles and run but immediately gives an error: "Access Violation at address 00401789". I can't figure out the reason for that?

Thanks for the help!
Oct 5 '06 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
int i=0;
while (!infile.eof()){
infile>>DataArray[i].Name;
i++.
This is because DataArray[i] access data in the vector that already exists but your vector is probably empty.

either set the vector size before you fill it using setsize (???) or write your data like this

Expand|Select|Wrap|Line Numbers
  1. int i=0;
  2. proPkaData data;
  3. while (!infile.eof()){
  4.     infile>>data.Name;
  5.     DataArray.push_back(data);
  6.     i++;
  7.  
Oct 5 '06 #2

P: 13
THanks a lot, that worked out fine.

Another problem though is that the last line of the txt-file is being read twice. This seems strange since I'm using

while(!infile.eof() )

as the condition for the loop. Is that something that comes "as a bonus" when using ifstream or why is the line being read twice?
Oct 5 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.