我正在用C++编写一些代码。在某个点(第44行:cout << commands_help[i];),它说有一个错误:“下标值不是数组” ...实际上,我使用的是列表,而不是数组...在函数“help()”中,我打印列表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;
}

最佳答案

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

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

08-26 17:03