Vector to Struct

I have this section for a program I'm working on where I am inputting into a vector within a structure. The syntax all seems correct, but I get this weird error I've never seen before.

(I'm using XCode)
It reads: Thread 1:EXC_BAD_ACCESS (code=1, address 0x0)

I've done a little reading, and I guess this has something to do with memory, but I'm too new at this to fully understand this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <vector>

struct fileSave
{
    vector<string> date;
}

int main ()
{
fileSave receipt;

//receipt.trip is defined earlier in the code and works fine
for (int i=0; i<receipt.trip; i++)
        {
            cout<<"Input date (mm/dd/yy): ";
            cin>>receipt.date[i];
        }

}


Is there a way to change the syntax or logic to avoid this type of error?
Last edited on
You can't use the operator[] with an empty vector, instead use a temporary variable to get the input from the user then push the value into the vector.

By the way that snippet shouldn't compile because of a missing semicolon that terminates the structure definition.

@jib, you're right. The semicolon is present in the original code, I just forgot to add it back in here afterward.

I did something simple like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
string y;
fileSave receipt;

for (int i=0; i<receipt.trip; i++)
        {
            cout<<"Input date (mm/dd/yy): ";
            cin>>y;
            
            receipt.date[i]=y;
        }
}


But I still get the same error. Any other ideas? Thanks
What part of:
You can't use the operator[] with an empty vector, instead use a temporary variable to get the input from the user then push the value into the vector.

Did you not understand?

Deadmittens,

You've misunderstood what jlb was tring to convey. Something like this:

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
#include <iostream>
#include <string>
#include <vector>

struct FileSave {
	std::vector<std::string> dates;
};

int main() {

	FileSave receipt;

	const int number_of_receipts = 2;
	for (int i = 0; i < number_of_receipts; ++i) {

		std::string date;

		std::cout << "Input date (mm/dd/yy): ";
		std::cin >> date;

		receipt.dates.push_back(date);

	}

	return 0;
}
@jin, wasn't aware of push_back, must've missed it in my reading.

@xismn, thanks for the clarification.

It works now, thank you both.
priority_queue< ClTableau, deque<ClTableau>, less<ClTableau> > priority ;
vector<ClTableau>ptrTableau;
list<int> liste;
list<int>::iterator it;

//Ajouter un element apres une position donnee

cout<<"Entrez une position : ";
cin>>position;
cout<<"Entrez un nombre : ";
cin>>nbr;

it = liste.begin();

for(int ctr = 0;ctr<position;ctr++){

it++;
}

liste.insert(it,nbr);



for(auto it = map.cbegin(); it != map.end(); it++)
cout<<"Nom complet : "<<(*it).first<< endl<<"numero de telephone : "
<<(*it).second<<endl;



map[nomComplet] = numero;
Topic archived. No new replies allowed.