Q:

How to change a digit in string to integer rather than its ASCII code?

Question : Write a program in a C++ to display the sum of digits present in a text file.
--> 
#include<iostream.h>  
#include<fstream.h>  
int main()  
{  
 ifstream f1("Fees.txt");  
 int sum=0;  
 char n;  
 while(f1.eof()==0)  
 {  
  f1>>n;  
  if(isdigit(n))  
   {  
   sum=sum+n;  
   }  
 }  
    cout<<sum;  
}  

I know the program's not working because string is changed to digit,( 1 changes to its ASCII code 49 instead of 1)
Please guide me
And is there a better way to approach the question?
UPDATE Ok so I changed the line sum+=n to sum+=n-'0'.
Still the program only seems to be working when there is a special character in addition to numbers in the text file Fees.txt.
  Example:
1 2 9

This does not work
1 2 9ok

This does work, any idea what's going on here?

A:

As you point out, the ASCII codes for digits do not start at zero, which is your problem. Luckily though, they do lie in a continuous range, so all you need to do is change the line:
sum=sum+n;

to
sum += (n - '0');

