首页 > 解决方案 > 通过输入名称和年份从特定结构中获取数据

问题描述

我正在为那些想要轻松查看他们拥有的葡萄酒的人构建一个葡萄酒库存系统,该系统会自动获取其市场价格和生产年份。

这个程序应该从下面代码中看到的多个预定义结构中获取一个结构,用户只需输入名称和年份,以便打印整个结构,例如,我输入“ Greenock creek Roennfelt road shiraz ”和年份“ 2002 ”然后它输出如下所示的整个结构。我正在考虑使用 read 或 get 命令,但在研究我应该如何做之前,我想问问是否有更有效的方法来做到这一点。

下面的结构只是连接到主文件的第二个 c++ 文件中大量预定结构中的一个。

如果可以的话,这在 C++ 中是否可行,你会如何建议继续?

不同文件中的结构:

struct red1 // one of the predetermined structs 
{
    string name = "Greenock Creek Roennfeldt Road Shiraz";
    double year = 2002;
    string place = "Australia";
    double price = 295.00;
    string type = "Redwine";
};

主文件输入:(这部分不是 100%,但它只是为了说明我的意思。

for (int i = 3; i < 10; i++)
    {
        string str; //input for data
        cout << "Please enter the data of your Wine: " << endl;
        cout << "Enter name: ";
        getline(cin, wine.name);
        cout << endl << "Enter year: ";
        getline(cin, wine.year);
        cout << endl;
        cout << "your entered data: " << endl;
        printwine(wine);

        wineinventory.push_back(wine);  // store in vector
    }

标签: c++struct

解决方案


我不明白你为什么想要有几个结构。我认为您只需要一个,然后为不同的葡萄酒创建不同的实例。为了这个例子,我将只使用年份和名称:

#include <vector>
#include <string>
#include <iostream>

struct wine {
    int year;
    std::string name;
};

// custom output operator to insert a wine into a ostream
std::ostream& operator<<(std::ostream& out, const wine& w) {
    out << "year: " << w.year << " " << w.name;
    return out;
};

int main() {

    // fill a vector with different wines
    std::vector<wine> wines { {2001,"the red one"}, {2005,"the white one"}};

    // select a year
    int year = 2001;

    // pick the ones with matching year and print them
    for (auto& w : wines) {
        if (w.year == year) std::cout << w << "\n";
    }
}

这将打印:

year: 2001 the red one

推荐阅读