#include <stdio.h>
#include <string.h>
int add(char s[])
{
char p[3];
int i=0, j=0, sum=0;
for(i=0;s[i]!='\0';i++)
{
if(isdigit(s[i])&&isdigit(s[i+1])&&isdigit(s[i+2])&&!isdigit(s[i+3])&&!isdigit(s[i-1]))
{
p[0]=s[i];
p[1]=s[i+1];
p[2]=s[i+2];
sum+=atoi(p);
}
}
return sum;
}
Above I tried writing the code to add only three digit numbers within the string text but it is not working. Can't figure out what the problem is.
char p[3]
can not hold 3 characters. You need to have extra byte for the null terminator. You can declare it as charchar p[4]
and domemset
to avoid confusion with null termination as following:Let me know, if you have any concerns.