Error while computing ascii to decimal
Hi all,
I have written a program that converts a string of ascii numbers into a decimal number. For example, if I enter 49 57 56 52 (ascii representations for 1 9 8 4) then it should give me 1984. My program gives me 4555 instead. Below is my code, please suggest changes. Thank you.
Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char nelements[100];
/*nelements is the input string to be converted to decimal consisting of nelements*/
int n,i,dec=0;
/*n is the number of elements in the string, i is the index value, dec is used to
build converted decimal integer, base0 is the ascii or ordinal value of character 0*/
printf("enter the number of elements");
scanf("%d",&n);
printf("enter the ascii value of elements");
for(i=1;i<=n;i++)
{
scanf("%s",&nelements[i]);
}
for(i=1;i<=n;i++)
{
nelements[i]-=48;
dec=dec*10+nelements[i];
}
printf("%d",dec);
system("pause");
return 0;
}