Find sum of integers in a file which contains any characters
You are given a text file which contains any type of characters. You have to find the sum of integer values.
Examples:
Input : text.txt
Let contents of test.txt be :
:-,,$%^5313&^*1)(*(
464sz29>>///11!!!
(*HB%$#)(*0900
Output : 6727
Input : text1.txt
Let contents of test.txt be :
234***3r3r()
()(0)34
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.
#include <bits/stdc++.h>
using namespace std;
int findSumOfIntegers()
{
ifstream f;
f.open( "text.txt" );
int sum = 0, num = 0;
string text;
while (f >> text) {
for ( int i = 0; text[i] != '\0' ; i++) {
if ( isdigit (text[i]))
num = 10 * num + (text[i] - '0' );
else {
sum += num;
num = 0;
}
}
}
sum += num;
return sum;
}
int main()
{
cout << findSumOfIntegers();
return 0;
}
|
Output:
6727 (for Input 1)
Last Updated :
06 Sep, 2017
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...