下标值不是数组(错误)

Subscripted value is not an array (error)

本文关键字:错误 数组 下标      更新时间:2023-10-16

我正在用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++;
    }
}

如果你有一个现代的编译器,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;
}