Vector Subscript out of range error

I create a program
which accept the name of the animal and age
And if I type stop the program should stop ans show me the input that I typed so far.
but when I type stop it create an out of range error.
How can I fix this issue?


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

using namespace std;

int main()
{
	string animalName;
	int animalAge;
	int numOfAni = 0;
	vector<string> nameOfAnimals;
	vector<int> age;

	for (int i = 0; i < 5; i++)
	{
		cout << "Enter animal #" << i + 1 << " 's name:";
		cin >> animalName;
		nameOfAnimals.push_back(animalName);
		// Options for exit the program.
		if (animalName == "STOP")
			break;
		else if (animalName == "Stop")
			break;
		else if (animalName == "stop")
			break;

		//Ask user to input age of animals
		cout << "Enter anial #" << i + 1 << " 's age:";
		cin >> animalAge;
		age.push_back(animalAge);
		numOfAni++;


	}


	//Deplay the author of the program.
	cout << endl;
	cout << "\nLab 1 created by Minje Ban Computer Science" << endl << endl;

	cout << "Animal" << "\n#\tName\tAge" << endl;

	for (int i = 0; i < nameOfAnimals.size(); i++)
	{
		cout << i + 1 << "\t" << nameOfAnimals[i] << "\t" << age[i] << endl;
	}

	cout << endl;


	system("pause");
	return 0;
}
I
Last edited on
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
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>

int main()
{
    std::vector<std::string> animal_names ;
    std::vector<unsigned int> animal_ages ;

    std::string name ;

    while( std::cout << "animal name? " && std::cin >> name && name != "STOP" && name != "stop" )
    {
        unsigned int age;
        std::cout << "age? " ;
        if( std::cin >> age ) // if the user entered a number for the age
        {
            animal_names.push_back(name) ;
            animal_ages.push_back(age) ;
        }
    }

    const auto w5 = std::setw(5) ; // http://en.cppreference.com/w/cpp/io/manip/setw
    const auto w15 = std::setw(15) ;

    std::cout << w5 << "Animal#" << w15 <<  "Name" << w5 << "Age" << '\n'
              << w5 << "-------" << w15 << "----" << w5 << "---" << '\n' ;

    for( std::size_t i = 0; i < animal_names.size(); ++i )
        std::cout << w5 << i+1 << std::setw(17) << animal_names[i] << w5 << animal_ages[i] << '\n' ;
}
Topic archived. No new replies allowed.