G-wizz03
G-wizz03

Reputation: 1

Why cannot I pass an ifstream variable to a function as a parameter?

I can run the first section outside of a function, however when I try to run the code with and ifstream object in a function I get the following error:

no match for operator>> (operand types are std::ifstream (aka std::basic_ifstream<char>} and const int)

CONSTANTS AND HEADERS

#include <iostream>

#include <fstream>

#include <iomanip>

using namespace std;

const int COLS = 5; //Declaring constant number of cols

const int ROWS = 7; //Declaring constant number of rows

const string FILENAME = "foodDrive.txt";

//Function Prototypes

The following works:

int main()
{
    int food[ROWS][COLS] = {0}; //declaring 2D array that will hold values

   ifstream inFile;

    inFile.open(FILENAME);

  for (int r = 0; r < ROWS; r++) //Outer loop for rows
  {
    for (int c = 0; c < COLS; c++) //inner loop for columns
    {
      inFile >> food[r][c];  //Take input from file and put into food
    }
  }
  inFile.close();
  

However this does not

void readArray(const int ary[][COLS],int rows)
{

   ifstream inFile;

    inFile.open(FILENAME);

  for (int r = 0; r < rows; r++) //Outer loop for rows
  {
    for (int c = 0; c < COLS; c++) //inner loop for columns

    {
      inFile >> ary[r][c];  //Take input from file and put into food
    }
  }
  inFile.close();
}

Upvotes: 0

Views: 124

Answers (1)

zalevskiaa
zalevskiaa

Reputation: 184

Remove const in function header, I guess it should help:

void readArray(int ary[][COLS], int rows) { ...

Upvotes: 2

Related Questions