Q:

C++ Program For Find The Sum of Integers In a File

0

Explanation:- 

First we have to create a file with extension (like .txt) after that by using the program we have to print the file in console screen. Always remember we have to read the file by line by line and also write the file sum line by line in another file name Sum.txt and one more thing file should be in the same folder in which our program already exists. We can give the file name in console screen so no need to give the filename in a program. So basically we have to take an input from one file and after the sum, we have to write the output in another file line by line. After the end of the program, one file will be created open the file you get the sum of the input file.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;
int main()
{
   ifstream inFile;
    char filename[20];
 
 cout<<"Enter The File Name With Extension\n";
 cin>>filename;
 
 inFile.open(filename);
 
 /*Here You Have To Create A File And put some data on it. 
Then Save the with Any Extension With File Name As Above Shown */
   
 if (!inFile)
   {
    cerr << "File example.txt not found." << endl;
    return -1;
   }
  
   ofstream outFile("sum.txt");
   /*Here You Have Sum Of File Line By Line Sum  */
   string line;
  
   while (getline(inFile, line))
   {
    if (line.empty()) 
 continue;

    istringstream iss(line);
    int sum = 0, next = 0;
    while (iss >> next) 
 sum += next;
    outFile << sum << endl;
   }

   inFile.close();
   outFile.close();
  
   cout<<"File Created Successfully Go To Sum.txt File And Open\n";
  
  return 0;

}

 

Input:

 

Output:

file created successfully go to sum.txt file and open 

 

File Output:

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Program To Count Number Of Characters In a Fil... >>
<< C++ Program To Read And Display File Line By Line ...