我正在尝试使用向量调用函数,由于某种原因,它说“期望的主表达式在']'之前。向量可以容纳任意数量的文件,具体取决于myfile中数字的数量,所以我不确定应该放在哪里。
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
using namespace std; // not recommended
double averageCalc(string[],int);
int main () {
double average;
string line;
ifstream myfile ("array_pgmdata.txt");
//int index = 0; // not needed
//string myArray[index]; // UB - if it even compiles, it's a VLA of size 0.
std::vector<std::string> myArray; // use this instead to be able to grow it
// dynamically
if (myfile) // open and in a good state
{
// while (! myfile.eof() ) // It'll not be eof when you've read the last line
// only when you try to read beynd the last line,
// so you'll add "line" one extra time at the end
// if you use that. Use this instead:
while(getline(myfile, line))
{
// myArray[index++] << line; // you have 0 elements in the array and
// can't add to it in any way
myArray.push_back(line);
}
}
else cout << "Unable to open file";
for(size_t idx=0; idx < myArray.size(); ++idx) {
std::cout << myArray[idx] << "\n";
}
average = averageCalc(myArray[], line); // error here
return 0;
}
double averageCalc(string nums[], int count)
{
int a, total, elements, averaged1, averaged2;
// string averaged2;
for(a = 0; a < count; a++)
{
total+=a;
elements++;
}
averaged1 = total / elements;
return averaged2;
}
答案 0 :(得分:0)
这里有一些问题。首先,您的函数averageCalc
需要一个类型为string[]
的参数,该参数是一个字符串数组。调用该函数时,您尝试将其传递给std::vector<string>
,它不是字符串数组,而是一个类。大概,您可能希望更改函数以采用向量,如下所示:
double averageCalc( const std::vector<string> & nums ); // no need for size now
您遇到的另一个问题是调用函数。调用它时,您将myArray[]
作为参数传递,这是编译器给您的错误。这是无效的语法,您只想传递myArray
。
答案 1 :(得分:0)
我认为错误发生的原因是,首先使用std::vector<std::string> myArray;
创建数组,所以数据为字符串类型,但是当您要计算平均值时,该函数需要一个int,double等值来执行数学。将字符串更改为int或使用函数将其转换:
int main()
{
string s = "12345";
// object from the class stringstream
stringstream geek(s);
// The object has the value 12345 and stream
// it to the integer x
int x = 0;
geek >> x;
// Now the variable x holds the value 12345
cout << "Value of x : " << x;
return 0;
}