This is what it's suppose to look like
我这样做正确吗?以及我需要做的另一种编码才能像这样显示。我必须模拟一个数据库来存储动物类型和动物类型计数。我必须使用并行数组进行数据存储。如果我将这个动态分配的数组不包含5个元素,那就更好了。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int MAX_RECORDS = 5;
const int ADD = 1, DISPLAY = 2, EXIT = 3;
void addAnimal();
void displayAnimal();
int main()
{
int choice, animal;
int a = 0;
do
{
cout << "How many animal records would you like to store (5 max): ";
cin >> animal;
cout << endl;
cout << "1. Add animal(s)" << endl;
cout << "2. Display animals" << endl;
cout << "3. Quit" << endl;
cout << endl;
do
{
cout << "Please enter a menu number: ";
cin >> choice;
if (choice <= 0 || choice > EXIT)
{
cout << "Error. Please try again.\n";
cout << endl;
}
} while (choice <= 0 || choice > EXIT);
// Create a muliway branch statement.
switch (choice)
{
case ADD:
addAnimal();
break;
case DISPLAY:
displayAnimal();
break;
case EXIT:
break;
}
} while (choice != EXIT);
cout << endl;
system("pause");
return 0;
}
void addAnimal()
{
string str;
do
{
cout << "Please enter an animal type (none to stop): " << endl;
getline(cin, str);
cout << "Enter the animal type's count: " << endl;
getline(cin, str);
} while (str != "goodbye");
}
void displayAnimal()
{
}
最佳答案
为了您的目的,我建议您使用std::vector<>
。以下是在C++中使用vectors的基本实现。
注意:您需要在顶部提到#include<vector>
。
#include<vector>
#include<iostream>
int main(){
std::vector<int> my_vec; // initializing a vector of integers
// To add anything to a vector, you can use
my_vec.push_back(5); // Adds 5 to my_vec
my_vec.push_back(6); // Adds 6 to my_vec
std::cout << my_vec[0] << std::endl; // Slicing from a vector
for(auto it:my_vec) std::cout << it << std::endl; // display contents
return 1;
}
我不能在这个答案中向您展示有关 vector 的所有信息,这是另一个巨大的话题。主要思想是它们是动态的,并且可以在运行时更改大小。与传统的静态数组相比。C++中的vectors
关于c++ - 并行数组以创建数据库来存储C++的动物类型和数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63680578/