int atoi (const char * str);
Convert string to integer
/* atoi example */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */
int main ()
{
int i;
char buffer[256];
printf ("Enter a number: ");
fgets (buffer, 256, stdin);
i = atoi (buffer);
printf ("The value entered is %d. Its double is %d.\n",i,i*2);
return 0;
}
Edit & Run
Enter a number: 73
The value entered is 73. Its double is 146.
atol
long int atol ( const char * str );
Convert string to long integer
/* atol example */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atol */
int main ()
{
long int li;
char buffer[256];
printf ("Enter a long number: ");
fgets (buffer, 256, stdin);
li = atol(buffer);
printf ("The value entered is %ld. Its double is %ld.\n",li,li*2);
return 0;
}
Edit & Run
Enter a number: 567283
The value entered is 567283. Its double is 1134566.
atof
double atof (const char* str);
Convert string to double
/* atof example: sine calculator */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atof */
#include <math.h> /* sin */
int main ()
{
double n,m;
double pi=3.1415926535;
char buffer[256];
printf ("Enter degrees: ");
fgets (buffer,256,stdin);
n = atof (buffer);
m = sin (n*pi/180);
printf ("The sine of %f degrees is %f\n" , n, m);
return 0;
}
Enter degrees: 45
The sine of 45.000000 degrees is 0.707101
strtod
double strtod (const char* str, char** endptr);
Convert string to double
/* strtod example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtod */
int main ()
{
char szOrbits[] = "365.24 29.53";
char* pEnd;
double d1, d2;
d1 = strtod (szOrbits, &pEnd);
d2 = strtod (pEnd, NULL);
printf ("The moon completes %.2f orbits per Earth year.\n", d1/d2);
return 0;
}
The moon completes 12.37 orbits per Earth year.
strtol
long int strtol (const char* str, char** endptr, int base);
Convert string to long integer
/* strtol example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char * pEnd;
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10);
li2 = strtol (pEnd,&pEnd,16);
li3 = strtol (pEnd,&pEnd,2);
li4 = strtol (pEnd,NULL,0);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
return 0;
}
The decimal equivalents are: 2001, 6340800, -3624224 and 7340031
strtoul
unsigned long int strtoul (const char* str, char** endptr, int base);
Convert string to unsigned long integer
/* strtoul example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtoul */
int main ()
{
char buffer [256];
unsigned long ul;
printf ("Enter an unsigned number: ");
fgets (buffer, 256, stdin);
ul = strtoul (buffer, NULL, 0);
printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
return 0;
}
Edit & Run
Enter degrees: 45
The sine of 45.000000 degrees is 0.707101