并行数组以创建数据库来存储C ++的动物类型和数量

如何解决并行数组以创建数据库来存储C ++的动物类型和数量

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

在这个答案中,我无法向您展示有关向量的所有信息,这是另一个巨大的话题。主要思想是它们是动态的,并且可以在运行时更改大小。与传统的静态数组相比。

vectors在C ++中

,

也许考虑使用std::map。您可以根据需要添加任意数量的动物。在这种情况下,每个动物的名字都会有一个相关的计数。在下面的示例中,程序退出时,将打印出您添加到地图的所有内容。

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<std::string,int> animal_database;
    std::string animal_name;
    std::string animal_count;
    std::string in_val;


    while (1)
    {
        std::cout << "Enter an animal name: ";
        std::cin >> animal_name;
        std::cout << "Enter animal count: ";
        std::cin >> animal_count;
        animal_database.insert(std::pair<std::string,int>(animal_name,std::stoi(animal_count)));
        std::cout << "Would you like to to add another animal?: [Y] or [N] ";
        std::cin >> in_val;
        if (in_val == "N" || in_val == "n")
            break;
    }

    for (std::map<std::string,int>::iterator it = animal_database.begin(); it != animal_database.end(); ++it)
    {
        std::cout << it->first << " " << it->second << std::endl;
    }

}
,

实现所需目标的另一种好方法是将面向对象的编程灌输到其中。这是一个简单的structure of Animals,可用于创建5个对象的数组。

以这个简短的例子

#include<iostream>

struct Animal{
    std::string name;
    int value;
    int weight;
}animals[5]; // creates an animal object array of size 5


int main(){
    for (int i = 0;i < 5;i++){
        std::cout << "Name of animal number " << i+1 << ": ";
        std::cin >> animals[i].name;
    }
    std::cout << animals[0].name;
}

输出:

Name of animal number 1: Tiger
Name of animal number 2: Lion
Name of animal number 3: Kangaroo
Name of animal number 4: Cheetah
Name of animal number 5: Dog
Tiger
Process returned 0 (0x0)   execution time : 23.463 s
Press any key to continue.

此程序中发生的情况的信息。

当我说struct Animal时,我正在创建一个structure。动物都具有相似的特征,例如体重,颜色,名称等。这些是将存在于结构体​​内的变量。

`animals [5]'。可以将其想象为一系列动物。具有共同属性(例如体重,颜色,名称等)的动物。假定用户想要创建一个新动物并输入其特征。我可以使用数组中的一个元素来执行此操作。让我们使用第一个。

std::cout << "Enter name: ";
std::cin >> animals[0].name;
std::cout << "Enter weight: ";
std::cin >> animals[0].weight;
std::cout << "Enter value: ";
std::cin >> animals[0].value;

现在animals的第一个元素已经初始化。您可以通过animals[0].attribute

进行访问

这种方法将有效地用于此类程序。请参阅this

在我的示例中,我使用循环获取了所有5个元素的输入。您可以在用户需要时执行相同的操作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-