Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

Program to input 2 numbers as strings and find the sum2 - C Code Bank


Program to input 2 numbers as strings and find the sum2
This program inputs 2 numbers in string format and adds it and diplays result. If there is any character, it gives "NOT A NUMBER" output. It uses a function to convert the characters to numbers.
                #include<string.h>
#include<stdio.h>


int convert(char *num)
{
int l,power,n=0,neg=0;
l=strlen(num);
power=1;
for(int i=0;i<l-1;i++)
{
 power*=10;
 }

for(i=0;i<l;i++)
{
 switch(num[i])
  {
   case '-':if(num[0]=='-')
	 neg=1;
	 else
	{ printf("\nNOT A NUMBER");return(NULL);   }
	 break;
   case '1':n+=(1*power);break;
   case '2':n+=(2*power);break;
   case '3':n+=(3*power);break;
   case '4':n+=(4*power);break;
   case '5':n+=(5*power);break;
   case '6':n+=(6*power);break;
   case '7':n+=(7*power);break;
   case '8':n+=(8*power);break;
   case '9':n+=(9*power);break;
   case '0':n+=(0*power);break;
   default:cout<<"NOT A NUMBER";return(NULL);
 }
power/=10;

if(power==0)
 power=1;

}

if(neg==1)
 n*=-1;

return n;
}

void main()
{
char *num1,*num2;
int a,b,s;
clrscr();
printf("\nA program that converts string in to numbers using a 

function and adds 2 numbers\n\n");
printf("\nEnter 2 numbers: ");
scanf("%s",num1);
scanf("%s",num2);
a=convert(num1);
b=convert(num2);
if(a!=NULL || b!=NULL)
{s=a+b;
printf("\na=%d   b=%d   and sum=%d",a,b,sum);
}
else
printf("\nNOT A NUMBER");

}
            
Comments
Sorry but there are no comments to display