下标值不是数组(错误)

时间:2016-09-12 07:31:09

标签: c++ arrays list

我正在用C ++编写一些代码。在某一点(第44行:cout << commands_help[i];)它表示存在错误:“下标值不是数组”......实际上我使用的是列表,而不是数组...在函数“帮助”中()“我在每个项目之间用commands_help打印列表\n的每个项目。我该怎么办?

代码:

#include <iostream>
#include <list>
#include <fstream>

using namespace std;

ifstream file;

// variables and arrays
string shell_symbol;

bool get_texture(){
    file.open("UsedTexture.txt", ios::in);
    if (file.is_open()){
        file >> shell_symbol;
        file.close();
        return true;
    } else {
        cout << "unable to open file";
        file.close();
        return false;
    }
}


list<string> commands_help = {
    "'help' ________________ Display this help page.",
    "'[command] info' ______ Display command purposes.",
    "'datetime' ____________ Can show date, time and calendar.",
    "'exit' ________________ Quit the MiSH."
};

long help_size = commands_help.size();

// functions / commands

int help() {
    int i = 1;
    commands_help.sort();
    while (i < help_size) {
        if (i < commands_help.size()){
            cout << commands_help[i];
        } else {
            break;
        }
    }
}

int main() {
    if (get_texture()) {
        string inp1;
        cout <<
        "\nThis is the MiSH, type 'help' or '?' to get a short help.\nType '[command] help' to get a detailed help.\n";
        while (true) {
            cout << shell_symbol;
            cin >> inp1;
            if (inp1 == "help" || inp1 == "?") {
                help();
            } else if (inp1 == "exit") {
                break;
            } else {

            }
        }
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您可以使用iteratoriterator类似于指向STL容器中元素的指针。例如:

int help() {
    list<string>::iterator it = commands_help.begin();
    while (it != commands_help.end()){
        cout << *it << '\n';
        it++;
    }
}

答案 1 :(得分:1)

如果您有一个现代编译器,C ++ 11将为您完成大部分工作:

#include <vector>
#include <string>
#include <iostream>

std::vector<std::string> commands_help =
{
    "'help' ________________ Display this help page.",
    "'[command] info' ______ Display command purposes.",
    "'datetime' ____________ Can show date, time and calendar.",
    "'exit' ________________ Quit the MiSH."
};

void help()
{
    for (auto line : commands_help)
    {
        std::cout << line << std::endl;
    }
}

int main()
{
    help();

    return 0;
}