我试图编写一个简单的程序,将数字转换为单词(即,它将 123 转换为 123)。代码完全编译。该代码使用指针和递归,在 C++ 中,就内存管理而言,我总是觉得这很棘手。任何人都可以指出以下代码在执行时是否会发生内存泄漏?提前致谢。
#include <iostream>
#include <string>
using namespace std;
char *convert_number(int, int);
const char *tens[]={"","ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
const char *words[]={"zero","one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen", "eighteen","ninteen"};
const char *place[]={"","thouands","million","billion","trillion"};
int main(int argc, char **argv)
{
int number,conv_num,places;
places=1;
char *string= new char[1000];
char *temp_string = new char[100];
cout<<"Enter a number:";
cin>>number;
string = convert_number(number,0);
cout<<"The word is :"<<string<<endl;
}
char *convert_number(int number,int places)
{
int divisor;
char *word;
int conv_num;
char *temp_string = new char[100];
word = new char[100];
divisor=10;
if (number>=1000)
{
conv_num = number % 1000;
number = (number-conv_num)/1000;
places++;
temp_string = convert_number(number,places);
word = strcat(word, temp_string);
word = strcat(word, place[places]);
word =strcat(word," ");
}
else
{
conv_num = number;
}
if (conv_num>=100)
{
word =strcat(word,words[conv_num/100]);
word =strcat(word," hundred ");
conv_num=conv_num%100;
}
if(conv_num >=20)
{
word=strcat(word,tens[conv_num/10]);
word =strcat(word," ");
if(conv_num%divisor>=1)
{
word=strcat(word,words[conv_num%divisor]);
word =strcat(word," ");
}
}
if(conv_num<20)
{
word=strcat(word,words[conv_num]);
word =strcat(word," ");
}
delete[] temp_string;
return word;
}