Calculating Sum of Integers of Unknown Length
My assignment, which I've attached (.pdf), is to write a C++ program that will accept a file containing an unknown number of integers as input. For each number in the input file, output the original number and the sum of the digits of the number.
Here's what I have so far:
Code:
// CS 1361
// Lab27
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
int main()
{
int number, digit, sumDigits;
ifstream fin; // Input File
ofstream fout; // Output File
fin.open("lab27.dat");
if (!fin)
{
cerr << "Error opening input file." << endl;
return 1;
}
fout.open("lab27.out");
if (!fout)
{
cerr << "Error opening output file." << endl;
return 1;
}
//output table heading
fout << setfill('-') << setw(27) << '-' << endl;
fout << "Number Sum of Digits" <<endl;
fout << setfill('-') << setw(27) << '-' << endl;
fout << setfill(' ');
while (fin >> number)
{
sumDigits = 0;
fout << number;
if (number != 0)
{
sumDigits = sumDigits + (number % 10);
}
}
fout << setfill('-') << setw(27) << '-' << endl;
//close the files
fin.close();
fout.close();
return 0;
I'm having some trouble with this... Any guidance will be hugely appreciated.