我正在尝试获取函数 getFilename
以提示用户读取哪个文件,然后将其传递给函数 readFile
以计算文件中的数字然后(使用 displayAverage
)显示文件中数字的平均值。
我是编码新手,无法弄清楚为什么它似乎没有使用 readFile
函数...程序会提示用户输入文件,但在那之后它只是输入一个空行。我是否正确地调用了函数并传递了参数?
void getFilename(char fileName[])
{
cout << "Please enter the filename: ";
cin >> fileName;
return;
}
float readFile(char fileName[])
{
cout.setf(ios::fixed);
cout.precision(0);
ifstream fin(fileName);
int sum = 0;
int numValue = 0;
float grades = 0;
float average= 0;
if (fin.fail())
{
cout << "Error opening file \"" << fileName << "\"";
return false;
}
while (!fin.eof())
{
fin >> grades;
sum += grades;
numValue++;
if (numValue != 10)
cout << "Error reading file \"" << fileName << "\"";
}
fin.close();
average = sum / 10;
return average;
}
void displayAverage(int average)
{
cout << average;
return;
}
int main()
{
char* fileName;
int average;
getFilename(fileName);
readFile(fileName);
displayAverage(average);
return 0;
}
最佳答案
您的程序有未定义的行为,因为 fileName
没有指向任何可以保存数据的有效内容。
除非您需要使用 char
数组来保存文件名,否则请使用 std::string
作为 fileName
。
std::string fileName;
如果您需要使用 char
数组来保存文件名,请使用
char fileName[FILENAME_LENGTH];
确保 FILENAME_LENGTH
足够大以满足您的需要。
关于c++ - 我是否正确传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48920927/