Mostafizur Rahman Mostafizur Rahman - 2 months ago 7
C++ Question

List of animals

I am trying to get the list of 5 animals name from the user and list them. So, far this is what I have. How can I output 1. animal1, 2. animal2 and so on.

#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
#include <set>

using namespace std;

int main() {

string animal;
int num_animals = 0;
cout << "Enter name of 5 animals of your choice. e.g., cat, <<
dog, etc.. "<< endl;
cout << ">>";
cin >> animal;
char temp; cin>> temp;

while (getline(cin, animal)) {

if (animal.empty() || cin.eof())
break;
else
++num_animals;
cout << ">> ";
}
int a[5];
int i;
char j= ':';
vector <string> animals;
animals.push_back (animal);
for ( i = 1; i < 6; )
cout << i++ <<j << animals << '\n';

cout << '\n' << "Bye.....";
return 0;
}

Answer

You have many errors and problems in your code. I'm just not going to bother to list them.

It looks like, you're new to c++, or to programming. You should check this: Why is "using namespace std" considered bad practice?

Now, let's try to write program of your needs.

First, make a std::vector of std::string:

std::vector<std::string> animalsList;

Now, loop to 5, and take input in each iteration, an animal name, and store it in the above created vector animalsList.

std::cout << "Enter name of 5 animals of your choice. e.g., cat, dog, etc..  "<< std::endl;
for (int i = 0; i < 5; i++){
    std::cout << ">> ";
    std::string animalName; // string to store an animal name.
    std::getline(std::cin, animalName); // Input an animal name.
    animalsList.push_back(animalName); // push the animal name to the vector
}

The above for loop will run 5 times, and input 5 different animal names, and push them to the vector animalsList, and after the loop, you'll have 5 different names in the vector.

Now, write another for loop to loop through all the names and print them on console.

for (int i = 0; i < animalsList.size(); i++) // here animalsList.size() will be 5
{
    std::cout << i + 1 << ": " << animalsList[i] << std::endl;
}

That's it. Now let's see the overall program:

#include <iostream>
#include <vector>
#include <string>

int main(){
    // declare a vector of string
    std::vector<std::string> animalsList;

    // Input 5 animal names and push them to the vector.
    std::cout << "Enter name of 5 animals of your choice. e.g., cat, dog, etc..  "<< std::endl;
    for (int i = 0; i < 5; i++){
        std::cout << ">> ";
        std::string animalName; // string to store an animal name.
        std::getline(std::cin, animalName); // Input an animal name.
        animalsList.push_back(animalName); // push the animal name to the vector
    }

    // output all the animal names.
    for (int i = 0; i < animalsList.size(); i++) // here animalsList.size() will be 5
    {
        std::cout << i + 1 << ": " << animalsList[i] << std::endl;
    }
    return 0;
}

See the above program live here.