c++ - 通过输入名称和年份从特定结构中获取数据

标签 c++ struct

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

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

下面的结构只是连接到主文件的第二个 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
    }

最佳答案

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

#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

关于c++ - 通过输入名称和年份从特定结构中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311360/

相关文章:

c++ - 如何在C++中按升序对结构数组进行排序

c - 不允许指向不完整类型的指针,定义全局结构

c++ - 字符串是动态分配的吗?

c++ - 在 C++ 中调用虚拟比较优先级

c++ - Mac OSX 和 Unix 快速问题

c - 双指针 typedef 结构数组

go - 传递结构

C 随机树指针警告(有时会崩溃)

c++ - 静态初始化数组 union 结构

c++ - 自由(): invalid pointer when implementing erase() of vector