469,300 Members | 2,165 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,300 developers. It's quick & easy.

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

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
2 2680
Banfa
9,064 Expert Mod 8TB
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
Curten
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.

Similar topics

7 posts views Thread by Bercin Ates via SQLMonster.com | last post: by
2 posts views Thread by jw56578 | last post: by
1 post views Thread by OGG | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by harlem98 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.