Derek H Derek H - 2 days ago 4
C++ Question

Trying to pass ifstream through a function?

I'm having trouble passing

ifstream
along with a
string
and an
int
. It won't let me just use
void readSettings(settings, key, numOfQuestions);
and then when I pass it as a reference, it says key and numOfQuestions are not type names. Any solution?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void readSettings(ifstream&, string&, int&);


int main() {

string key = "";
int numOfQuestions = 0;

void readSettings(ifstream& settings, key, numOfQuestions);

cout << key;
cout << numOfQuestions;

return 0;
}

void readSettings(ifstream& settings, string& key, int& numOfQuestions)
{
// To be completed

settings.open("settings.txt");

settings >> numOfQuestions;
settings >> key;

settings.close();

}

Answer

The statement in main:

void readSettings(ifstream& settings, key, numOfQuestions);

is a function declaration not a function call.

The following is a function call:

readSettings(settings, key, numOfQuestions);

Notice the differences.

Comments