every operation in separate funtion(note: input from file)

i am trying to do every operation in a separate funtion. in this code input, sum and output. but something i'm doing wrong i don't know. so please guide.

#include<iostream>
#include<fstream>
using namespace std;

void input() //function for input
{
ifstream fin;
fin.open("input.txt");

int a, b;

fin>>a;
fin>>b;

fin.close();
}

int add(int a, int b) //function for sum
{
int sum;

sum=a+b;

return sum;
}

void output(int sum) //function for output
{
cout<<sum;
}

int main()
{
int sum;

input();

sum=add(a, b);

output(sum);
}
In input() a/b are local variables. You cannot use them in for the add(). Change it e.g. like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<fstream>
using namespace std;

void input(int &a, int &b) //Note: Reference (&) is necessary so that the change of a/b is 'reflected' to the caller
{
ifstream fin;
fin.open("input.txt");

int a, b;

fin>>a;
fin>>b;

fin.close();
}

int add(int a, int b) //function for sum
{
int sum;

sum=a+b;

return sum;
}

void output(int sum) //function for output
{
cout<<sum;
}

int main()
{
int a, b;
int sum;

input(a, b);

sum=add(a, b);

output(sum);
} 


Please use code tags: [code]Your code[/code]
Read this: http://www.cplusplus.com/articles/z13hAqkS/
you have to move the declaration of a, b outside the input function. local variable has a lifetime as long as the function call.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
#include<fstream>
using namespace std;

// int & means passby reference
void input(int & a, int & b)  //function for input
{
    ifstream fin;
    fin.open("input.txt");
    //int a, b;
    fin >> a;
    fin >> b;
    fin.close();
}

int add(int a, int b)   //function for sum
{
    int sum;
    sum = a + b;
    return sum;
}

void output(int sum)    //function for output
{
    cout << sum;
}

int main()
{
    int sum;
    // a, b is declared inside input function, when function is end, the a, b disappeared.
    // you need to declare a, b here, and pass to input function by reference.
    int a, b;
    input(a, b);
    sum = add(a, b);
    output(sum);
}

This is the right version of it. Hoping this will help you
thanx you all. :)
Topic archived. No new replies allowed.