Reading file and storing to a vector

Hi,

I am trying to build a feature into my program that allows for information to be read from a text file and then stored into a corresponding vector. My program compiles but it blows up when i try to open the file. Any help is appreciated.

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
  void openFile(vector<Address>& record, Address& nAddress)

{
	ifstream import;
	string input;
	int i = 0;
	cout << endl;
	
	import.open("address.txt");
	
	while(getline(import, input))
	{
		
		getline(import, input, ';');
		record[i].id = input;
		getline(import, input, ';');
		record[i].firstname = input;
		getline(import, input, ';');
		record[i].lastname = input;
		getline(import, input, ';');
		record[i].email = input;
		getline(import, input, ';');
		record[i].phone = input;
		getline(import, input, ';');
		record[i].unit = input;
		getline(import, input, ';');
		record[i].street = input;
		getline(import, input, ';');
		record[i].city = input;
		getline(import, input, ';');
		record[i].province = input;
		getline(import, input, ';');
		record[i].country = input;
		getline(import, input);
		record[i].postal = input;
		record.push_back(nAddress);
		i++;
	}
	
	
	import.close();
	
	cout << "Import was succesful" << endl;
	cout << endl;
hey, your code is trying to index a vector that has no elements which causes run time error
i.e Vector Record has no elements yet. trying to index it with codes like
record[i] will causes an error
you could do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

void openFile(vector<Address>& record) 
{
	ifstream import("address.txt");
	if(!import) return ; // Check if input stream is valid but i would advice you pass this 
	                             //stream as a parameter to this function 

	Address nAddress; // i beleive this is a struct
        string input; // no need for this as you can access struct variables directly
	
	while(getline(import, nAddress.id, ';') &&
		getline(import, nAddress.firstname, ';') &&
		getline(import, nAddress.lastname, ';') &&
		getline(import, nAddress.email, ';') &&
		getline(import, nAddress.phone, ';')  //...........others here)
	{
			record.push_back(nAddress);
	}
	
}


the whole point is to setup your struct and record.push_back(the struct) without using indexes
Last edited on
Topic archived. No new replies allowed.