Signup/Sign In

C++ Program For Reading A No. From File And Sum Of No. Line By Line Using File

In this tutorial, we will be learning how to read a number from a file and the sum of numbers line by line using files.

C++ Program For Reading a No. From File And Sum Of No. Line By Line Using File

Before moving to the implementation part, let's first understand the working of the algorithm:

First, we have to create a file with the extension (like .txt) after that by using the program we have to print the file on the 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 on the 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.

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

using namespace std;
//Ghanendra Yadav
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;

}


4 5 1 51 15 15 151 5 -1
2 2 2 2 5 4 4 -1
9 8 7 6 4 5 4 2 1 -1

File Created Successfully Go To Sum.txt File And Open
246
20
45

Conclusion

Here, in this tutorial, we have implemented the reading of a number from a file and the sum of numbers line by line using files.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.