Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 15th, 2012  |  syntax: None  |  size: 1.79 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Recursion with pointer and memory leak
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. char *convert_number(int, int);
  6.  
  7. const char *tens[]={"","ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
  8. const char *words[]={"zero","one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen", "eighteen","ninteen"};
  9. const char *place[]={"","thouands","million","billion","trillion"};
  10.  
  11.  
  12. int main(int argc, char **argv)
  13.  {
  14. int number,conv_num,places;
  15. places=1;
  16. char *string= new char[1000];
  17. char *temp_string = new char[100];
  18. cout<<"Enter a number:";
  19. cin>>number;
  20. string = convert_number(number,0);
  21. cout<<"The word is :"<<string<<endl;
  22. }
  23.  
  24. char *convert_number(int number,int places)
  25. {
  26. int divisor;
  27. char *word;
  28. int conv_num;
  29. char *temp_string = new char[100];
  30. word = new char[100];
  31. divisor=10;
  32.  
  33. if (number>=1000)
  34. {  
  35.     conv_num = number % 1000;
  36.     number = (number-conv_num)/1000;
  37.     places++;
  38.     temp_string = convert_number(number,places);    
  39.     word = strcat(word, temp_string);
  40.     word = strcat(word, place[places]);
  41.     word =strcat(word," ");
  42. }
  43. else
  44. {
  45.     conv_num = number;
  46. }
  47. if (conv_num>=100)
  48. {
  49.     word =strcat(word,words[conv_num/100]);
  50.     word =strcat(word," hundred ");
  51.     conv_num=conv_num%100;
  52. }
  53.  
  54. if(conv_num >=20)
  55. {
  56.  word=strcat(word,tens[conv_num/10]);
  57.  word =strcat(word," ");
  58.  if(conv_num%divisor>=1)
  59.  {
  60.     word=strcat(word,words[conv_num%divisor]);  
  61.     word =strcat(word," ");
  62.   }
  63. }
  64.  
  65. if(conv_num<20)
  66. {
  67.     word=strcat(word,words[conv_num]);
  68.     word =strcat(word," ");
  69. }      
  70. delete[] temp_string;      
  71. return word;
  72. }
  73.        
  74. char *temp_string = new char[100];  // first assignment
  75.  
  76. [...]
  77.  
  78. if (number>=1000)
  79. {  
  80. [...]
  81.     temp_string = convert_number(number,places);