c++ - 用 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++
解决方案
您已声明name
为十六个数组,并且读取十六个数组std::string
没有重载。getline
std::string
你想要string name
或者char name[16]
(我会选择前者)。
此外,该成员getline
仅处理char*
.
你需要“免费” getline
:
std::getline(std::cin, menu[i].name);
推荐阅读
- excel - 两个日期时间与 Excel 公式的区别
- azure - 创建 Web App Bot 时如何选择模板?
- git - 在 Git 中,如何配置必须使用 1 个 URL 而不是 2 个 URL(通过命令)
- angular - 有没有办法像我们在codeigniter中那样从角度7中的url获取片段
- python - 如何将python变量插入sql表
- hadoop - 应用程序 application_1576595769387_0004 失败 2 次,因为 AM Container for appattempt_1576595769387_0004_000002 以 exitCode:1 退出
- c++ - 为什么在 C++ 宏扩展为注释时出现“预期声明”错误?
- python - tesseract.exe 未安装或不在您的路径中
- c++ - 未定义的 new 运算符如何导致 C++ 中的未定义行为?
- cassandra - 我应该在 Cassandra-Driver 4.x 中为 localDataCenter 使用什么