无法解析C ++中的标识符[方法]名称

时间:2018-02-01 02:14:17

标签: c++ netbeans

所以我不是编程的新手,但是我是C ++的新手。
我在Next()方法中收到此错误,names[]数组突出显示。有人可以帮忙吗?

typedef string text;
text Next(text t);
int main() {

text rock;
text names[10] = {"basalt", "dolomite", "granite", "gypsum", "limestone", "marble",
"obsidian", "quartzite", "sandstone", "shale"};
cout<<"Enter a rock: \n";
cin>>rock;
cout<<Next(rock);


return 0;
}

text Next(text t) {
for (int i = 0; i < 10; i++) {
    if (names[i].compare(t) == 0) {
        return names[i + 1];
    }
}
return "Off boundary or not found";
}

1 个答案:

答案 0 :(得分:-1)

试试这个,它应该有用。我在最后一行代码中添加了一些解释。

typedef string text;
text Next(text t, text namesArr[], int size);    // modified

int main() {

    text rock;
    text names[10] = {"basalt", "dolomite", "granite", "gypsum", "limestone", "marble", "obsidian", "quartzite", "sandstone", "shale"};
    cout<<"Enter a rock: \n";
    cin>>rock;
    cout<<Next(rock, names, 10);    // modified

    return 0;
}

text Next(text t, text namesArr[], int size) {    // modified
    for (int i = 0; i < size; i++) {
        if (namesArr[i].compare(t) == 0) {
            if (i==9) {
                return namesArr[0]; 
            }
            else {
                return namesArr[i + 1]; 
            }
        }
    }

    return "Not found"; // modified , it should never be out of bound since you specify the fixed array size, and also because you do the checking i==9
}

代码中的问题是您text names[10]函数中定义了main()。因此,该数组仅对主函数而言是本地的。

如果您想在Next()函数中使用该数组,则可以

1。使names[]数组全局化。即。

typedef string text;
text Next(text t);

// defined globally here, any function can now access this array.
text names[10] = {"basalt", "dolomite", "granite", "gypsum", "limestone", "marble", "obsidian", "quartzite", "sandstone", "shale"};

int main() {
    // your original code here, without the "names[]" declaration.
}

text Next(text t) {
    // your code here, but with the "i==9" case checking to prevent out of bound
}

2。将names[]数组传递给具有数组大小的函数

这是在我的回答开始时完成的