动物名单

时间:2016-10-07 16:37:19

标签: c++

我正在尝试从用户那里获取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;
}

1 个答案:

答案 0 :(得分:1)

您的代码中存在许多错误和问题。我只是不愿意列出它们。

看起来,你是c ++或编程的新手。你应该检查一下:Why is "using namespace std" considered bad practice?

现在,让我们尝试编写您需要的程序。

首先,制作一个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,并在循环之后,您&# 39; ll在向量中有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;
}

请参阅上述计划live here