c++ - 如何使数组以单词而不是数字的形式出现
问题描述
我正在构建一个 bin 大小计算器,我也需要 bin 的类型作为单词而不是数字出现
我尝试为每个 bin 名称制作单独的字符串,但没有成功。
#include<iostream>
#include <string>
using namespace std;
int main() {
int i;
cout << "Welcome to Jasons bin size measurer!\n\nPlease answer the following questions: " << endl;
cout << " Please Tell us your waste type " << endl << "By typing the corrosponding number: " << endl;
char waste[11][50] = { " ", "General Waste = 1","Mixed Heavy Waste = 2", "Timber Waste = 3","Green Garden Waste = 4 ","Soil/Dirt = 5","Clean Fill/Hard Fill = 6","Concrete only = 7","Bricks only = 8", "Cardboard/Paper = 9","Metal only = 10" };
for (i = 0; i < 11; i++) {
cout << waste[i] << "\n";
}
cin >> waste[i];
int length = 0;
int width = 0;
int height = 0;
cout << "\nPlease enter the length: ";
cin >> length;
cout << endl << "Please enter the width: ";
cin >> width;
cout << endl << "Please enter the height: ";
cin >> height;
int volume = length * width * height;
cout << endl;
if (volume < 3) {
cout << "A 2m " << waste << endl;
}
if (volume < 4 && volume > 2) {
cout << "\nA 3m bin ";
}
if (volume < 5 && volume > 3) {
cout << "\nA 4m bin will meet your requirements";
}
if (volume < 7 && volume > 4) {
cout << "\nA 6m bin will meet your requirements";
}
if (volume < 9 && volume > 6) {
cout << "\nA 8m bin will meet your requirements";
}
if (volume < 11 && volume > 8) {
cout << "\nA 10m bin will meet your requirements";
}
if (volume < 13 && volume > 10) {
cout << "\nA 12m bin will meet your requirements";
}
if (volume < 22 && volume > 12) {
cout << "\nA 21m bin will meet your requirements";
}
if (volume < 25 && volume > 21) {
cout << "\nA 24m bin will meet your requirements";
}
if (volume < 32 && volume > 24) {
cout << "\nA 31m bin will meet your requirements";
}
if (volume > 31) {
cout << "\nUnfortunatly we do not have that bin size";
return 0;
}
}
我期望输出是x bin will meet your requirements(bin name)
但是它出来了X bin will meet your requirements 008FFA1C
。
解决方案
您的代码中有几个问题。让我们从您在数组中分配 11 个字符串但您读取第 12 个的事实开始。从这一刻开始,一切都可能发生,这是未定义的行为。
接下来,仅当volume > 31
这绝对是错误时才返回 0。
最后,输出二维数组而不是数组元素:
cout << "A 2m " << waste << endl;
你的意思
cout << "A 2m " << waste[0] << endl;
或类似的东西?
推荐阅读
- flutter - 在 Flutter 中限制应用程序中的 Googlemap 大小
- bash - FSL - 我可以将 fsf 文件(程序设置文件)中的路径设置为当前工作目录吗?
- javascript - useState Hook - 如何将项目附加到有状态数组的末尾?
- docker - 创建 droplet 后如何添加 docker?
- algorithm - 给定一个循环链表,找到一个合适的头,使得值的运行总和永远不会为负
- sql - 如何在 spark/sql 中过滤掉所有重复的电话号码
- flutter - 未为类型“x”定义运算符“+” - Flutter
- python - “QuerySet”对象没有“已批准”属性
- javascript - 只有 index.js 在 reactjs 中有效
- javascript - onclick 按钮可根据当前 URL 将用户从 HTML 站点带到 AMP 站点