I'm getting an error around a function that I'm using. The whole program is meant to print either a Roman Numeral or Integer when given a Roman Numeral or Integer by the user.
This function in particular is meant to calculate an Roman Numeral when given an integer. It's now sending me to a _fastfail (still new, I haven't seen this before). Fastfail's "copy details" gets this:
"Unhandled exception at 0x0137CFE9 in HughesProject9.0.exe: Stack cookie instrumentation code detected a stack-based buffer overrun. occurred".
When it was running, the integer at the top of the function threw the correct "integer" back, and same with counter. Here's the function:
string intToRoman(int integer)
{
char romanArray[10];
int M = 0;
int D = 0;
int C = 0;
int L = 0;
int X = 0;
int V = 0;
int I = 0;
int counter = 0;
int i = 0;
M = integer / 1000;
D = ((integer % 1000) / 500);
C = ((integer % 500) / 100);
L = ((integer % 100) / 50);
X = ((integer % 50) / 10);
V = ((integer % 10) / 5);
I = (integer % 5);
counter = M + D + C + L + X + V + I;
cout << "Integer: " << integer;
cout << "Counter: " << counter;
while (counter > 0)
{
for (int j = 0; j < 10; j++)
{
if (M > 0)
{
romanArray[i] = 'M';
i++;
counter--;
}
}
for (int j = 0; j < 3; j++)
{
if (D > 3)
{
romanArray[i] = 'C';
i++;
counter--;
}
else
{
romanArray[i] = 'D';
i++;
counter--;
}
}
for (int j = 0; j < 3; j++)
{
if (C > 3)
{
romanArray[i] = 'L';
i++;
counter--;
}
else
{
romanArray[i] = 'C';
i++;
counter--;
}
}
for (int j = 0; j < 3; j++)
{
if (L > 3)
{
romanArray[i] = 'X';
i++;
counter--;
}
else
{
romanArray[i] = 'L';
i++;
counter--;
}
}
for (int j = 0; j < 3; j++)
{
if (X > 3)
{
romanArray[i] = 'V';
i++;
counter--;
}
else
{
romanArray[i] = 'X';
i++;
counter--;
}
}
for (int j = 0; j < 3; j++)
{
if (V > 3)
{
romanArray[i] = 'I';
i++;
counter--;
}
else
{
romanArray[i] = 'V';
i++;
counter--;
}
}
for (int j = 0; j < 3; j++)
{
if (I > 0)
{
romanArray[i] = 'I';
i++;
counter--;
}
}
string calcRoman(romanArray);
return calcRoman;
}
}
I don't think your algorithm for generating the Roman numeral equivalent is correct. I passed in 100
, and this is the array it was constructing
i 0 ╠╠╠╠╠╠╠╠╠╠
i 3 DDD╠╠╠╠╠╠╠
i 6 DDDCCC╠╠╠╠
i 9 DDDCCCLLL╠
i 12 DDDCCCLLLX
i 15 DDDCCCLLLX
i 15 DDDCCCLLLX
Which is certainly not the roman numeral for 100. It looks like you need to recheck the else
portions of your for
loops, they are inserting chars when not needed
for (int j = 0; j < 3; j++)
{
if (D > 3)
{
romanArray[i] = 'C';
i++;
counter--;
} else
{
romanArray[i] = 'D';
i++;
counter--;
}
}
D
was zero but this code still inserts 3 'DDD'. You likely need something like
} else if (D > 0) {