C Help Filestream Write a program that reads the values from
C++ Help: Filestream
Write a program that reads the values from a file and writes the sum of all multiples of 2
or 5 into another file. Your program must contain separate functions for reading and writing a file.
Please explain your code-Will give a thumbs up. Thanks!
Solution
num.txt (Save this file inside D:Drive .Then the path of the file pointing to this file is D:\\\ um.txt )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
__________________________________________
CPP code
#include <iostream>
#include <fstream>
using namespace std;
//Declaring Global variable
int sum=0;
//Function declarations
void readFromFile();
void writeToFile();
/* Function implementation which will
* read the numbers from the file and calculates the sum of
* the numbers which are multiples of 2 or 5
*/
void readFromFile()
{
int number;
//fileInput reference
ifstream dataIn;
//Opening input file
dataIn.open(\"D:\\\ um.txt\");
while(dataIn>>number)
{
if(number%2==0 || number%5==0)
{
sum+=number;
}
}
//closing the input stream
dataIn.close();
}
/* Function implementation which will
* display the sum into another text file
*/
void writeToFile()
{
//fileoutput reference
ofstream myfile;
//Opening the file
myfile.open (\"D:\\\ um1.txt\");
//Writing the contents to the file
myfile <<\"The Sum of Multiples of 2 or 5 is :\"<<sum<<endl;
//closing the output stream.
myfile.close();
}
int main()
{
//Calling the function which will read the file
readFromFile();
//Calling the function which will write the output to file
writeToFile();
return 0;
}
____________________________________________________
output:
num1.txt (We will get this file in D Drive.As we specified the path D:\\\ um1.txt)
The Sum of Multiples of 2 or 5 is :130
____________________________________Thank You

