john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

string to int conversions

/* john pfeiffer 22-aug-07 program to convert a string to an integer and back, 
updated 09nov07 , updated 22jun08 to show gets/puts 
*/

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    int i = 0;
    char str[11];  
    /* The maximum integer size is 2 ^ 31 - 1 = positive 2,147,483,647. 
    (signed int means 1 bit to indicate positive) 
    so we shouldn't need more than 10 chars + 1 for the null char*/

    printf("enter a big number (e.g. 1234567890):");
    gets(str);   /* automatically appends a null char /0 to the end of the string */
    printf("puts(str) = ");
    puts(str);   /* this will cause an error without the null char at the end */
    printf("\nWe can do fun things with strings: ");
    i=0;
    while( str[i] != '\0' )
    {   printf("%c ",str[i]);  
        i++;
    }

    i=atoi(str);
    printf("\n\nafter i=atoi(str) --> i=%d, %%s is %s\n",i,str);

    sprintf(str, "%d", i);  /* appends a null char to end of string */

/* d=signed int base 10, f=float, s=ptr to array, c= char, */
/* p=prints val of ptr (val of mem location), */
/* o= unsigned int, input in base 8 (octal). Digits 0 - 7 only. */

    printf("\nsprintf(str,""%%d"",i), int i=%d and back to a string=%s\n",i,str);
    return 0;
}

  • « string reverse
  • passing pointers to functions »

Published

Aug 22, 2007

Category

c

~171 words

Tags

  • c 95
  • conversions 1
  • int 2
  • string 18
  • to 63