Not Yet Answered # Arabic Numbers to Roman Numerals

Discussion Starter Gabriela_2 tinstaafl 854 Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...

0

excuse me if it is a total bullshit, i'm a beginer in c++

```
#include <iostream>
using namespace std;
int main()
{
int n, a, b;
const char* r;
const char* m;
cin >> n;
if (n > 3000 || n <= 0)
{
cout << "Invalid Number!\n";
}
else
{
a = n / 1000;
if (a == 1)
{
r = "M";
}
if (a == 2)
{
r = "MM";
}
if (a == 3)
{
r = "MMM";
}
b = n / 100;
if (b == 1)
{
m = "C";
}
if (b == 2)
{
m = "CC";
}
if (b == 3)
{
m = "CCC";
}
if (b == 4)
{
m = "CD";
}
if (b == 5)
{
m = "D";
}
if (b == 6)
{
m = "DC";
}
if (b == 7)
{
m = "DCC";
}
if (b == 8)
{
m = "DCCC";
}
if (b == 9)
{
m = "CM";
}
cout << r << m;
}
return 0;
}
```

1

A couple of things:

When you're programming in c++ it is much easier to use `string`

instead of `char*`

.

When you're joining strings(concatenating), since strings are immutable, a stringstream(<sstream>) is very handy. Otherwise, each time you join 2 strings you end up making a brand new string.

As for the logic, you seem to be on the right track.

One thing that can help is using the `string(size_t, char)`

constructor. Consider, once you know how many Thousands you'll need, you can simply say `string(x,'M')`

to represent that value.

Also if you subtract each leftmost digit once you've determined it's value, the rest is ready to be evaluated.

Consider this code segment which will handle the thousands and hundreds:

```
string ArabicToRoman(int input)
{
stringstream ss;
int temp = 0;
if (input > 3000 || input < 1)
{
return "Invalid Number!";
}
//If the input is 1000 or more or if the thousands digit is a 1,2, or 3
if (input > 999)
{
temp = input / 1000;
ss << string(temp,'M');
input -= temp * 1000;
}
//If the hundreds digit is a 9
if (input > 899)
{
ss << "CM";
input -= 900;
}
//If the hundreds digit is 5,6,7, or 8
else if (input > 499)
{
temp = (input / 100) % 5;
ss << "D" << string(temp, 'C');
input -= temp * 100;
}
//If the hundreds digit is a 4
else if (input > 399)
{
ss << "CD";
input -= 400;
}
//If the hundreds digit is a 1,2, or 3
else if (input > 99)
{
temp = input / 100;
ss << string(temp, 'C');
input -= temp * 100;
}
```

At this point you should be able to follow the pattern to finish it. The stringstream has a str() that will return the string represented in the stringstream(`return ss.str();`

).

Recommended Articles

Hi. so this is actually a continuation from another question of mineHere but i was advised to start a new thread as the original question was already answered.

This is the result of previous question answered :

code for the listbox - datagridview interaction

At the top of the code ...

the function that I created to find the ...