[英]error: expected primary-expression before ']' token
我收到错误消息:
']'标记前的预期主要表达式`
在这行上:
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;
}
}
}
在main()中,函数调用错误:
berakna_histogram_abs(histogram[], textRad);
应该:
berakna_histogram_abs(histogram, textRad);
仅在函数声明中需要[]
,而在调用函数时则不需要。
您在main()
对函数berakna_histogram_abs
调用是错误的,应该是:
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){...}
// ^^^^^^
同样在您的主目录中,您尝试将字符串作为参数传递,因此您的代码应为:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.