Putting functions in .h file

Ok, so this is the situation. I'm trying to put all my functions in a .h file instead of having them all in the main.cpp file. My original program is much longer so i thought I would try to figure it out on a smaller scale. Anyway, I have found that the program complies when I do not use the ifstream variable but I need this for my actual program. the error message simply reads that the ifstream was not declared in this scope. "This" being the main.cpp. I have been playing around with this for awhile and I have googled this but can't seem to find the answer. I'm sure its a simple fix, something small that I am missing but I do not know what it is. Can someone help me.



1
2
//sum.h
int sum(int a, int b, ifstream in);




1
2
3
4
5
6
7
//sum.cpp
#include "sum.h"
int sum(int a, int b, ifstream in)
{
        return (a+ b);

} 



1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "sum.h"
#include <fstream>

int main()
{
    int x;
        ifstream in;
        x = sum(3,4, in);
        std::cout << x;
        return 0;

}


Try adding your header guards to the sum.h file.

1
2
3
4
5
6
7
//sum.h
#ifndef SUM_H
#define SUM_H

int sum(int a, int b, ifstream in);

#endif 
line 8: std::ifstream in;
I'm trying to figure out why you are trying to pass an fstream object to your function and am drawing a blank. It's possible using pointers, but passing a string for the file name and opening the file inside the sum function would be easier.
You should probably include fstream and iostream in your header file.
Last edited on
Pass the ifstream parameter by reference.

1
2
3
4
5
6
7
//sum.h
#ifndef sumH
#define sumH

int sum(int a, int b, std::ifstream & in);

#endif 


1
2
3
4
5
6
7
8
//sum.cpp
#include <fstream>
#include "sum.h"

int sum(int a, int b, std::ifstream & in)
{
    return (a + b);
}


1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>
#include "sum.h"

int main()
{
    int x;
    std::ifstream in;
    x = sum(3,4, in);
    std::cout << x;
    return 0;
}
newbieg wrote:
It's possible using pointers, but passing a string for the file name and opening the file inside the sum function would be easier.

Maybe the file is already open and the position is part way through the file. Simply passing the file name would mean starting all over again from the beginning of the file, which is a different matter.
it was actually the std::ifstream. Thank you very much.

Also newbieg, this is not my actual program. My actual program has too much other things going on in it so i thought i would put something simple together in order to make it easier for people to help me. So in this particular program of course it seems silly to pass the ifstream, but then again this programs purpose was to figure out how to pass an ifstream, not to use one.

Thanks so much for all the help. Now my program has other errors but ill see if i can debug those.
Topic archived. No new replies allowed.