I am writing a program to convert ints to roman numerals. this is the function that gets called when the user enters a number. it works just fine for number 1-99, but then it will either crash, or give bogus data for any numbers higher that 99. any pointers as to where i am going wrong with this?

string intToRoman(int num) {
  string roman;
  int h,t,o;
  char *ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
  char *tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
  char *hundreds[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
  char *thousands[] = {"","M","MM","MMM","MMMM","MMMMM"};

  if (num =< 5000) {
    th = num / 1000;
    h = num / 100;
    t = num / 10;
    o = num % 10;
    roman = roman + thousands[th] + hundreds[h] + tens[t] + ones[o];
  } else
    roman = "Please enter a smaller number\n";

  return roman;

}

> t = num / 10;
If num is 1234, then t is 123
This is WAY beyond the end of your array.

thank you for the advice. i got it working just fine now. still getting used to the mod function. never saw it before this semester. i used this code to get it to work for anyone else who happens to have a similar problem

if (num <= 5000) {
    th = num / 1000;
    h = (num / 100) %10;
    t = (num %100) / 10;
    o = num % 10;
    roman = roman + thousands[th] + hundreds[h] + tens[t] + ones[o];
  }

thank you for the advice. i got it working just fine now. still getting used to the mod function. never saw it before this semester. i used this code to get it to work for anyone else who happens to have a similar problem

if (num <= 5000) {
    th = num / 1000;
    h = (num / 100) %10;
    t = (num %100) / 10;
    o = num % 10;
    roman = roman + thousands[th] + hundreds[h] + tens[t] + ones[o];
  }

Sorry, but that's a convoluted mess.

How about something like:

if (num <= 5000) {
    th = num / 1000;
    num = num % 1000;  // get rid of the 1000s

    h = num % 100;
    num = num % 100;   // get rid of the 100s

    t = num / 10;
    o = num % 10;
    roman = roman + thousands[th] + hundreds[h] + tens[t] + ones[o];
  }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.