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

Issue

This Content is from Stack Overflow. Question asked by G-wizz03

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**’

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



Solution

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

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


This Question was asked in StackOverflow by G-wizz03 and Answered by zalevskiaa It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?