【问题标题】:Filling struct field with getline()用 getline() 填充结构字段
【发布时间】:2019-12-18 10:35:17
【问题描述】:

大家好,我是这个论坛的新手,我想就我编写的代码寻求一些建议。 我仍在学习如何编码,我的老师让我创建一个带有字符串字段的静态分配结构数组:我的问题是我真的不知道如何使用 getline() 来填充它,所以我得到了一个来自我的 IDE 的错误:
[错误] 没有匹配函数调用 '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;
    }
}


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

附:我的 IDE 是 Dev-C++

【问题讨论】:

标签: c++ compiler-errors getline


【解决方案1】:

您已将name 声明为十六个std::strings 的数组,并且没有getline 重载用于读取十六个std::strings 的数组。

您想要string namechar name[16](我会选择前者)。

另外,getline 成员只处理char*

你需要“免费”getline:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 2020-05-20
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2019-08-24
    相关资源
    最近更新 更多