错误:令牌之前的预期主表达式']'

error: expected primary-expression before ']' token

本文关键字:表达式 令牌 错误      更新时间:2023-10-16

我得到错误:

应在']'标记`之前使用主表达式

在线:

berakna_histogram_abs(histogram[], textRad);

有人知道为什么吗?

const int ANTAL_BOKSTAVER = 26;  //A-Z
void berakna_histogram_abs(int histogram[], int antal);
int main() {
   string textRad = "";
   int histogram[ANTAL_BOKSTAVER];
   getline(cin, textRad);
   berakna_histogram_abs(histogram[], textRad);
   return 0;
}
void berakna_histogram_abs(int tal[], string textRad){
   int antal = textRad.length();
   for(int i = 0; i < antal; i++){
      if(textRad.at(i) == 'a' || textRad.at(i) == 'A'){
        tal[0] + 1;
      }
   } 
}

In main()函数调用错误:

berakna_histogram_abs(histogram[], textRad);

应该是:

berakna_histogram_abs(histogram, textRad);

您只需要在函数声明中使用[],但在调用函数时不需要。

您对函数berakna_histogram_abs的调用在main()中是错误的,应该是:

berakna_histogram_abs(histogram, textRad);
//                             ^

函数声明中的[]表示它接受一个数组,您不必在函数调用中使用它。

您有另一个错误:

函数berakna_histogram_abs的原型是:

void berakna_histogram_abs(int histogram[], int antal);
//                                          ^^^

main()定义和之前

void berakna_histogram_abs(int tal[], string textRad){...}
//                                    ^^^^^^

此外,在您的main中,您正试图传递一个字符串作为参数,因此您的代码应该是:

void berakna_histogram_abs(int histogram[], string antal);
int main()
{
    // ...
}
void berakna_histogram_abs(int tal[], string textRad){
    //....
}

最后一件事:尝试传递引用或const引用,而不是值:

void berakna_histogram_abs(int tal[], string& textRad)
//                                          ^

您的最终代码应该看起来像:

const int ANTAL_BOKSTAVER = 26;  //A-Z
void berakna_histogram_abs(int histogram[], const string& antal);
int main() {
   string textRad = "";
   int histogram[ANTAL_BOKSTAVER];
   getline(cin, textRad);
   berakna_histogram_abs(histogram, textRad);
   return 0;
}
void berakna_histogram_abs(int tal[], const string& textRad) {
   int antal = textRad.length();
   for(int i = 0; i < antal; i++){
      if(textRad.at(i) == 'a' || textRad.at(i) == 'A'){
        tal[0] + 1;
      }
   } 
}

您将表传递给函数是错误的。你应该简单地:

berakna_histogram_abs(histogram, textRad);

此外,您首先声明的内容:

void berakna_histogram_abs(int histogram[], int antal);

但比你试图定义的:

void berakna_histogram_abs(int tal[], string textRad){}

这就是编译器认为第二个参数是int而不是string的方式。函数的原型应该与声明一致。

传递histogram[]
时出错仅通过histogram
在参数中,您已将第二个参数定义为int,但在定义函数时,您保留了第二个变量为string类型
更改初始定义

void berakna_histogram_abs(int histogram[], int antal);

void berakna_histogram_abs(int histogram[], string textRad);