vector subscript out of range error

I can't figure out why I keep getting an error when I try to print my vector. If I use anything other than names.size() in the for loop than I get the vector subscript out of range error. If I use names.size() then I dont get an error, but it wont print anything.

The problem is in my wackGoose function. The code isn't done for that function, I just never got past the first part.

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
void introduction();
//Introduce program and programmer
void getNames(vector<string> names);
//fills the vector with names
void getGoose(int&goose);
//gets the gooseth entry from the user
void wackGoose(vector<string> names, int goose);
//eliminates the gooseth entry over and over
template <class myType>
void interchange(myType&a, myType&b);
//interchanges two names


int main()
{
	introduction();
	cout << endl << endl;

	vector<string> names;
	int goose;

	getNames(names);
	getGoose(goose);
	wackGoose(names, goose);


	cin.ignore();
	cin.get();
	return 0;
}


//DEFINITIONS SECTION

void getNames(vector<string> names)
//fills the vector with names
{
	string name;
	ifstream fin;
	fin.open("C:/Users/Josh/Desktop/goosey.txt");

	int count =0;
	while(fin >> name)
	{
		names.push_back(name);
		cout << names[count] << "  ";
		++count;
	}

	cout << endl << endl;
}


void getGoose(int&goose)
//gets the gooseth entry from the user
{
	do{
	cout << "Enter the position of the GOOSE: ";
	cin >> goose;
	}while(goose<1);
}


void wackGoose(vector<string> names, int goose)
//eliminates the gooseth entry over and over
{
	for(int index=0; index<names.size()-1; ++index)
	{
		cout << names[index];
	}
}

template <class myType>
void interchange(myType&a, myType&b)
//interchanges two names
{
	myType temp = a;
	a=b;
	b=temp;
}
I don't see anything there which would cause you problems.

If I understand what you are doing, you should pass a vector<string>& names.
Also, is there a reason why you are excluding the last element of the vector? Use:
for (int index = 0; index < names.size(); ++index)

Hope this helps.
If I use anything other than names.size() in the for loop than I get the vector subscript out of range error. If I use names.size() then I dont get an error, but it wont print anything.


Why would you use anything other than names.size() unless you only wanted to print some of the vector but not all? It would help if you posted an example that specifically demonstrates the problem that you said you have.

Moreover, you can use iterators and avoid the for loop completely.
http://www.cplusplus.com/reference/std/iterator/ostream_iterator/
Are you sure that getNames is working correctly? It could be that your vector isn't being filled at all.
Topic archived. No new replies allowed.