English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

The following program is working properly with no error.

//***
#include
#include
#include
using namespace std;

void GetAndWrite(ifstream inFile);

int main()
{
ifstream inFile;
int number;

inFile.open("input.txt");
inFile >> number;
cout << "number" << " is " << number;
}
//***

But when i want to pass the input file to a function, some errors happen. i mean the following program doesn't work.

//*************************************
#include
#include
#include
using namespace std;

void GetAndWrite(ifstream inFile);

int main()
{
ifstream inFile;

inFile.open("input.txt");

GetAndWrite(inFile);
}

void GetAndWrite(ifstream inFile)
{
int number;
inFile >> number;
cout << "number" << " is " << number;
}
//***

i used Dev-C++ compiler, but why the second program is not working?

2006-11-04 13:50:08 · 2 answers · asked by ___ 4 in Computers & Internet Programming & Design

2 answers

EDIT:
Make the argument to the function to be a POINTER not the ifstream object itself. Then it will compile and likely work.
In other words use:
void GetAndWrite(ifstream * inFile) // the argument is a pointer
{
int number;
*inFile >> number; //dereference the pointer
cout << "number" << " is " << number;
}

int main()
{
ifstream inFile;

inFile.open("input.txt");

GetAndWrite(&inFile); //send a pointer into the function through the argument
}

2006-11-04 14:33:10 · answer #1 · answered by DadOnline 6 · 0 0

It will be better if you pass olny the string to the function. Do not pass the file pointer. Then inside the function you can do same thing as you have done in first program.

2006-11-04 18:28:53 · answer #2 · answered by manoj Ransing 3 · 0 0

fedest.com, questions and answers