Dalan
Dalan

Reputation: 37

Am I passing parameters correctly?

I'm trying to get the function getFilename to prompt the user for which file to read and then pass that to the function readFile which calculates the numbers in the file and then (using displayAverage) display the average of the numbers in the file.

I'm new to coding and can't figure out why it doesn't seem to be using the readFile function... the program prompts the user for the file but after that it just inputs a blank line. Am I calling the functions & passing the parameters correctly?

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;
}

Upvotes: 1

Views: 65

Answers (1)

R Sahu
R Sahu

Reputation: 206617

Your program has undefined behaviour since fileName does not point to anything valid that can hold data.

Unless you are required to use an array of chars to hold the filename, use std::string for fileName.

std::string fileName;

If you are required to use an array of chars to hold the filename, use

char fileName[FILENAME_LENGTH];

Make sure FILENAME_LENGTH is large enough for your needs.

Upvotes: 1

Related Questions