sanskarid94
BAN USERWe can use ASCII values(int) of the characters of the string to Parse it to an Integer.Below is the code for my implementation :
#include<string.h>
#include<stdio.h>
#include<math.h>
int canStringBeParsed(char*);
int parseInt(char*);
main(){
char *str;
int stringLength;
int parsedInt;
printf("Enter String Length: ");
scanf("%d", &stringLength);
str = (char*)malloc(stringLength*sizeof(char));
printf("Enter the String: ");
fflush(stdin);
gets(str);
if(canStringBeParsed(str)){//Handling Program when given String can't be parsed to Integer
parsedInt = parseInt(str);
printf("The Parsed Integer is: %d", parsedInt);
}
else{
printf("The given String can't be parsed to Integer");
}
}
int canStringBeParsed(char *str){
int i;
int len = strlen(str);
for(i=0; i<len; i++){
if(str[i] < 48 || str[i] > 57){
return 0;
}
}
return 1;
}
int parseInt(char *str){
int i, len, parsedInt=0;
len = strlen(str);
char charInt;
for(i=0; i<len; i++){
charInt = str[len-1-i];
parsedInt = parsedInt + pow(10, i)*(charInt-48);//Subtract 48 to convert (48-57) to (0-9)
}
return parsedInt;
}
Replarenccabral, Title searcher at Fisher Foods
In real estate business and law, a title search or property title search is the process of examining public records ...
RepFannieRamirez, Accountant at A9
I am a technically skilled Payroll bookkeeper responsible for the full charge bookkeeping function. My expertise includes knowledge of accepted ...
Replleongardner, Animator at 247quickbookshelp
I am a writer and television producer living in the Corpus Christi area. I have always been fascinated by the ...
RepDarikaLee, Applications Developer at ADP
I am a knowledgeable and performance-driven Network Administrator with a comprehensive background in managing servers, maintaining software/hardware, performing backups ...
----SOME MODIFICATION IN MY CODE----
A function
can be added to check whether the given string can be parse to integer or not.So below is the final code :
- sanskarid94 July 01, 2015