打印一份动物清单

Print out a List of animals

本文关键字:一份 打印      更新时间:2023-10-16

我正在努力从用户获得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;
}

您的代码中有许多错误和问题。我只是不想麻烦地列出它们。

看起来,你是c++新手,或者是编程新手。您应该检查一下:为什么使用命名空间std"被认为是不好的做法?

现在,让我们试着根据你的需要写一个程序。

首先,制作std::stringstd::vector:

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