I get a bus error in my code. With this code, I am trying to convert numbers to words, but I know there is a flaw in my logic. But before that, when I compile and run this code using g ++ on mac, I try to make this code as it is, and I get a bus error. Any help would be appreciated.
When I run the code, I get the following output. I have debug messages to keep track of where the error occurs.
Enter a number: 1234
main 1: numbers are: 234
Function1: Number is 234
two
two hundred
34 Function2: Number is 34
Function3: Number is 34
Bus error: 10
#include <iostream> #include <string> using namespace std; char *convert_number(int); char *tens[]={"","ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; char *words[]={"zero","one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen", "eighteen","ninteen"}; char *place[]={"","hundred","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=" "; if(number>=1000) { while(number>=1) { conv_num = number % 1000; cout<<"main 1:numbers are:"<<conv_num<<endl; temp_string=convert_number(conv_num); string =strcat(string,temp_string); string =strcat(string," "); number = 0;// (number-conv_num)/1000; cout<<"main 2:numbers are:"<<endl; //cout<<conv_num<<":"<<number<<endl; } } else { string = convert_number(number); string =strcat(string," "); } cout<<"Main: The word is :"<<string<<endl; } char *convert_number(int number) { int divisor; char *word; word = new char[100]; divisor=10; cout<<"Function1: Number is "<<number<<endl; if (number>=100) { word =strcat(word,words[number/100]); cout<<word<<endl; word =strcat(word," hundred "); cout<<word<<endl; number=number%100; cout<<number; } cout<<"Function2: Number is "<<number<<endl; if(number >=20) { word=strcat(word,tens[number/10]); word =strcat(word," "); if(number%divisor>=1) { word=strcat(word,words[number%divisor]); word =strcat(word," "); } } cout<<"Function3: Number is "<<number<<endl; if(number<20) { word=strcat(word,words[number]); word =strcat(word," "); } cout<<"Returning word:"<<word; return word; }