Advertisement
DavidsonDFGL

Int para Char/String

Nov 15th, 2013
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <math.h>
  4. int main()
  5. {
  6.          int tamanho = 0;
  7.      int numero  = 589;
  8.      int num     = numero;
  9.      
  10.      //obtenho o tamanho do numero com divisoes sucessivas por 10
  11.      for( ; num != 0; num=num/10,tamanho++);
  12.      
  13.      //aloco um ponteiro para char, definido pelo tamanho * tamanho de 1 char
  14.      char *numeroString = (char *)malloc(tamanho * sizeof(char));
  15.    
  16.      /*
  17.       * neste ponto gravo o inteiro no char da seguinte forma:
  18.       *
  19.       * numero = 213
  20.       * num    = 213 / 100 = 2 (resultado truncado)
  21.       * numero = 213 % 100 = 13
  22.       *
  23.       * num    = 13 / 10 = 1
  24.       * numero = 13 % 10 = 3
  25.       *
  26.       * num    = 3  / 1 = 3
  27.       * numero = 3  % 1 = 0
  28.      */
  29.      
  30.      for(int i=tamanho; i>=1; i--)
  31.      {
  32.          int pot = pow(10,i-1);
  33.          int num = numero / pot;
  34.          numero  = numero % pot;
  35.          
  36.          *(numeroString + (tamanho-i) ) = (char)(num+48);
  37.      }
  38.  
  39.      //percorro meu 'vetor'
  40.      for(int i=0; *(numeroString+i) != '\0'; i++)
  41.      {
  42.          printf("String: %c\n",*(numeroString+i));   
  43.      }
  44.      
  45.      //libero a memoria
  46.      free(numeroString);
  47.      
  48.          /*
  49.      * se estas executando em um terminal, use a seguinte linha para compilar:
  50.      * gcc -std=c99 -lm po.c -o po
  51.      */
  52.  
  53.      return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement