C Program to convert string to integer

C Program to convert string to integer

Solution 1:

#include
#include
int main(){
char str[50];
int number;

//Accepting a numer in string format
printf("Enter any number as a string : ");
scanf("%s",str);

//Converting string into the number;
number = atoi(str);
if(number==0 && str[0]!='0')
printf("\nInvalid number");
else
printf("\n Equivalent number is : %d",number);
return 0;
}




Solution 2:

#include
#include
#include
#include

char * toString(int);
int main(){
int number;
char *string;

//Accepting a number from user
printf("Enter any integer number : ");
scanf("%d",&number);

//Checking number is valid or not
if(isdigit(number)==0){
printf("\nInvalid number");
//exit(1); //to exit from program
}

//Converting int to string
string = toString(number);

//printing the string in console
printf("\nEqivalent string: %s",string);
return 0;
}

//function to conver int into string
char * toString(int num){
static char str[50];
char *ptr =(char *) #
int i,length=0,temp,le;
temp=num;
while(temp){
temp = temp/10;
length++;
}
le=length;
printf("le %d",length);
for(i=0;i<=le;i++){
printf("%d",num/pow(10,length) + 48);
num= num + (pow(10,length--));
}
str[i]='\0';
return str;
}

No comments:

Post a Comment