C program to Convert "integer in string" to actual Integer using "strtol" library function
#include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>
#include
<errno.h>
int
main(int argc, const char * argv[])
{
/* Define temporary variables */
char value[10];
char *eptr;
long result;
/* Copy a value into the variable */
/* It's okay to have whitespace before the
number */
strcpy(value, " 123");
/* Convert the provided value to a decimal
long */
result = strtol(value, &eptr, 10);
/* If a conversion could not be done,
display the error
message and exit */
if (result == 0)
{
printf("Conversion error occurred:
%d", errno);
exit(0);
}
/* Display the converted result */
printf("%ld decimal\n", result);
/* Copy a hexadecimal value into the
variable */
strcpy(value, "0x19e");
/* Convert the provided value to a decimal
long */
result = strtol(value, &eptr, 16);
/* If a conversion could not be done,
display the error
message and exit */
if (result == 0)
{
printf("Conversion error occurred:
%d", errno);
exit(0);
}
/* Display the converted result */
printf("%lx hexadecimal\n",
result);
return 0;
}
Output:
$gcc
-o main *.c
$main
123
decimal
19e
hexadecimal