首页 > 解决方案 > 用 getline() 填充结构字段

问题描述

大家好,我是这个论坛的新手,我想就我编写的代码征求一些建议。我仍在学习如何编码,我的老师让我创建一个带有字符串字段的静态分配结构数组:我的问题是我真的不知道如何使用 getline() 来填充它,所以我得到了一个来自我的 IDE 的错误:
[Error] no matching function for call to 'std::basic_istream::getline(std::string [16]

这是我用来定义结构的代码:

typedef struct{
    string name[16];
    int price;
}dish;


还有我用来填充它的函数:

void insertDish(dish menu[], int fill){
    for(int i=0; i<fill; i++){
        cout<<"Enter name and price of dish "<<(i+1)<<": "<<endl;
        cout<<"Name: ";
        cin.getline(menu[i].name);

        cout<<"Price: ";
        cin>>menu[i].price;
        cout<<endl;
    }
}


如果有拼写错误,我很抱歉,但英语不是我的主要语言,我尝试翻译代码,以便您更容易理解它。

PS 我的 IDE 是 Dev-C++

标签: c++compiler-errorsgetline

解决方案


您已声明name为十六个数组,并且读取十六个数组std::string没有重载。getlinestd::string

你想要string name或者char name[16](我会选择前者)。

此外,该成员getline仅处理char*.

你需要“免费” getline

std::getline(std::cin, menu[i].name);

推荐阅读