Список животных

Я пытаюсь получить список из 5 названий животных от пользователя и перечислить их. Итак, пока это то, что у меня есть. Как я могу вывести 1. animal1, 2. animal2 и так далее.

#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;
}

-3

Решение

В вашем коде много ошибок и проблем. Я просто не собираюсь их перечислять.

Похоже, вы новичок в C ++ или в программировании. Вы должны проверить это: Почему "используя пространство имен std" считается плохой практикой?

Теперь давайте попробуем написать программу для ваших нужд.

Во-первых, сделать std::vector из std::string:

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

Теперь перейдем к 5и взять входные данные в каждой итерации, имя животного, и сохранить его в созданном выше векторе 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
}

Выше for цикл будет работать 5 раз и ввод 5 разные имена животных, и подтолкнуть их к вектору animalsListи после цикла у вас будет 5 разные имена в векторе.

Теперь напишите другой for Цикл, чтобы перебрать все имена и распечатать их на консоли.

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

Вот и все. Теперь давайте посмотрим общую программу:

#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;
}

Смотрите вышеупомянутую программу живи здесь.

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector