Related Articles

Related Articles

Find sum of integers in a file which contains any characters
  • Difficulty Level : Medium
  • Last Updated : 06 Sep, 2017

You are given a text file which contains any type of characters. You have to find the sum of integer values.


Input : text.txt 
Let contents of test.txt be : 

Output : 6727

Input : text1.txt 
Let contents of test.txt be : 

Output : 274

Steps :
1. To open the file in only read mode we can use ifstream library
2. Iterate through all rows of the file and find all integers
3. If integer found then store it in temp variable because there is a chance that next character can be an integer
4. Add temp value in final result if any character found except integers and set temp = 0 again
5. If last element is an integer then we have to add temp after loop if it isn’t then the value of temp will already be zero. So sum will not affected.





// C++ implementation of given text file which
// contains any type of characters. We have to
// find the sum of integer value.
#include <bits/stdc++.h>
using namespace std;
// a function which return sum of all integers
// find in input text file
int findSumOfIntegers()
    ifstream f; // to open the text file in read mode"text.txt");
    int sum = 0, num = 0;
    // One by one read strings from file. Note that
    // f >> text works same as cin >> text.
    string text;
    while (f >> text) {
        // Move in row and find all integers
        for (int i = 0; text[i] != '\0'; i++) {
            // Find value of current integer
            if (isdigit(text[i])) 
                num = 10 * num + (text[i] - '0');            
            // If other character, add it to the
            // result
            else {
                sum += num;
                num = 0; // and now replace
                         // previous number with 0
    sum += num;
    return sum;
// Driver program to test above functions
int main()
    cout << findSumOfIntegers();
    return 0;



6727 (for Input 1)

This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :