Write a c++ program that reads the contents of a file containing integer numbers, then for
each number calculate the sum of its digits and print it on the screen.

Respuesta :

Answer:

#include<iostream>

#include<conio.h>

#include<fstream>

using namespace std;

main()

{

int number, sum=0;

ifstream inputfile;

inputfile.open("path of file");

while (inputfile>>number)

{

sum = sum + number;

}

inputfile.close();

cout<<"\nThe sum of numbers in Input file = "<< sum;

getch();

}

Explanation:

In this program, a variable named as number with integer datatype to get input from input file. fstream is the library that is used to read, write from and to the file respectively. inputfile is the name of file inwhich data is stored. In input.open file, the path of file is required that need to be read and sum. In while loop, each time number get a value from file and sum it with previous values until all the values has been added. then file will be closed using inputfile.close command. Output will be shown through cout command.

Q&A Education