首页 > 解决方案 > 如何使数组以单词而不是数字的形式出现

问题描述

我正在构建一个 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

标签: c++arrayschar

解决方案


您的代码中有几个问题。让我们从您在数组中分配 11 个字符串但您读取第 12 个的事实开始。从这一刻开始,一切都可能发生,这是未定义的行为。

接下来,仅当volume > 31这绝对是错误时才返回 0。

最后,输出二维数组而不是数组元素:

cout << "A 2m " << waste << endl;

你的意思

cout << "A 2m " << waste[0] << endl;

或类似的东西?


推荐阅读