打印一份动物清单
Print out a List of animals
我正在努力从用户获得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::string
的std::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;
}
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 我的字符串数组一次打印出前两个字符串
- 为什么完整的字符串没有一次打印,但是当我尝试逐个字符打印时
- 为什么一次打印一个字符比提前连接它们慢
- 如何将.txt文件中的多维数组放入代码中,并一次打印一行
- 如何一次打印带有空格的整个wchar_t?(C++)
- 随机打印程序,尽管 sleep() 功能,一次打印多个输出
- C++一次打印一个单词的字符串,计算字符数和字符数
- 一种打印多地图地图的方法
- 一次打印 2 个字节的十六进制数字
- 我可以退回一份推荐信吗
- 有没有办法通过 int 指针一次打印整数
- 打印一份动物清单
- 非静态成员函数,为每个对象创建生成一份机器码副本
- 为什么代码一开始打印0
- 为什么我会从我的职能部门收到一份会议声明
- 想在Hudson C/C++上找到一份工作
- 如何一次打印出多个字符
- C++ : 如何检测矢量中的重复项<string>并打印一份副本?
- 一次C++打印多个相等键的值