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;
}
#include<iostream>
#include<fstream>
usingnamespace 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);
}
#include<iostream>
#include<fstream>
usingnamespace 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