酷代码 AI
菜单
服务商

C++实现零食数量统计:输入验证、循环条件与容器初始化要点解析

```cpp #include <iostream> #include <map> using namespace std; int main() { map<int, int> snackCount; // 使用map存储种类编号和对应数量 int snackType; cout << "请输入零食种类编号(1~10),输入0结束:" << endl; while (cin >> snackType && snackType != 0) { if (snackType >= 1 && snackType <= 10) { snackCount[snackType]++; // 对应种类数量加1 } else { cout << "编号无效,请输入1~10的数字。" << endl; } } cout << "统计结果:" << endl; for (int i = 1; i <= 10; i++) { cout << "种类" << i << ": " << snackCount[i] << "包" << endl; } return 0; } ``` 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 输入验证必须严格,防止无效数据影响统计结果 循环结束条件要明确,避免无限循环 容器初始化确保所有种类都有默认值,避免访问未初始化的键 ######[AI写代码神器 | 248点数解答 | 2025-12-13 11:51:38]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]