Reading and Summing Numbers From a File

C++C++Beginner
Practice Now

Introduction

In this lab, we will learn how to read numbers from a file and then sum them line by line, outputting the results to another file. By following the steps in this tutorial, you will learn how to write a C++ program that:


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") cpp/BasicsGroup -.-> cpp/arrays("`Arrays`") subgraph Lab Skills cpp/variables -.-> lab-96163{{"`Reading and Summing Numbers From a File`"}} cpp/data_types -.-> lab-96163{{"`Reading and Summing Numbers From a File`"}} cpp/operators -.-> lab-96163{{"`Reading and Summing Numbers From a File`"}} cpp/strings -.-> lab-96163{{"`Reading and Summing Numbers From a File`"}} cpp/conditions -.-> lab-96163{{"`Reading and Summing Numbers From a File`"}} cpp/while_loop -.-> lab-96163{{"`Reading and Summing Numbers From a File`"}} cpp/arrays -.-> lab-96163{{"`Reading and Summing Numbers From a File`"}} end

Create a new C++ file

Create a new file named file_sum.cpp in the ~/project directory.

touch ~/project/file_sum.cpp

Include necessary libraries

To work with files in C++ we need to include the <iostream> and <fstream> libraries in our program. Add the following code to your file_sum.cpp file:

#include <iostream>
#include <fstream>

using namespace std;

Prompt the User for the File Name

We will prompt the user for the file name. Add the following code to your file_sum.cpp file:

int main()
{
    char fileName[50];
    cout << "Enter file name: ";
    cin.getline(fileName, 50);
    ifstream inFile(fileName);
    ofstream outFile("sum.txt");
    string line;
}

Here we declare a char array fileName to hold the file name that the user will enter. We then prompt the user to enter the file name and store it in the fileName array. Finally, we create an ifstream object to open the input file inFile, and an ofstream object to create the output file outFile. We also declare the line string which will be used to store each line of the input file.

Read the File and Sum Numbers

We will now write the code to read the file and sum the numbers on each line. For each line in the file, we will read the numbers using a stringstream object, sum them and write the sum to the output file. Add the following code to your file_sum.cpp file:

while (getline(inFile, line))
{
    int sum = 0;
    stringstream ss(line);
    int num;
    while (ss >> num)
    {
        sum += num;
    }
    outFile << sum << endl;
}

Here, we use a while loop to read each line of the input file, storing the line in the line string. We then initialize the sum variable with 0, create a stringstream object named ss that holds the contents of each line. We then extract each number from the stringstream to num and increment the sum variable with each number. After all the numbers on the line have been processed, we write sum to the output file outFile.

Close Files and Notify User

Lastly, we need to close the input and output files and inform the user that the file has been processed. Add the following code to your file_sum.cpp file:

inFile.close();
outFile.close();
cout << "File processed successfully." << endl;
return 0;

Compile and Run the Code

Compile the file_sum.cpp code using the following command:

g++ file_sum.cpp -o file_sum

Run the code with the following command in the terminal:

./file_sum

You will be prompted to enter the file name that you want to process. Enter the name and hit enter. The program will read the file, sum the numbers line by line, and write the results to a new file named sum.txt.

Full code

Here's the full code of the file_sum.cpp file:

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

using namespace std;

int main()
{
    char fileName[50];
    cout << "Enter file name: ";
    cin.getline(fileName, 50);
    ifstream inFile(fileName);
    if (!inFile)
    {
        cerr << "Unable to open file" << endl;
        return -1;
    }
    ofstream outFile("sum.txt");
    string line;

    while (getline(inFile, line))
    {
        int sum = 0;
        stringstream ss(line);
        int num;
        while (ss >> num)
        {
            sum += num;
        }
        outFile << sum << endl;
    }

    inFile.close();
    outFile.close();
    cout << "File processed successfully." << endl;
    return 0;
}

Summary

In this lab, we learned how to read a file, sum its numbers line by line, and write the results to another file by using the C++ standard libraries <iostream> and <fstream> and the stringstream class. Now you should be able to handle files and use many of the basic file operations in your C++ programs.

Other C++ Tutorials you may like