First Error:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
//Line 12-33 and line 41-57 all have this problem
for (int i = 0; i < 20; i++) //Looks pretty innocent, right?
{
if (num1[i] == 'I' || num1[i] == 'V' || num1[i] == 'X' || num1[i] == 'L' || num1[i] == 'C' || num1[i] == 'D' || num1[i] == 'M')
{
if (num1[i] == 'I')
numf = numf + 1;
if (num1[i] == 'V')
numf = numf + 5;
if (num1[i] == 'X')
numf = numf + 10;
if (num1[i] == 'L')
numf = numf + 50;
if (num1[i] == 'C')
numf = numf + 100;
if (num1[i] == 'D')
numf = numf + 500;
if (num1[i] == 'M')
numf = numf + 1000;
}
else
cout << "Its in invalid";
}
| |
The line of the for loop looks pretty innocent, right? But think about it. What if the user inputs a number, say "IIIX", that has less than 20 chars? Once you pass the "X", you encounter the null terminator. It doesn't match any of the valid chars, so it will output "invalid". AND once after the null terminator, the memory is unused by cin, because there are no more chars to read in, which gives you stack garbage. You can fix this by:
for(int i = 0;i < 20 && num1[i] != '\0';i ++)
Second Error:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
if (oper == '+')
{
sum = numf + nums ;
cout << sum;
}
if (oper == '-')
{
sum = numf - nums;
cout << subtract; //You are outputting subtract, but you are storing the result in sum
}
if (oper == '*')
{
sum = numf * nums;
cout << Multiply; //Here also
}
if (oper == '/')
{
sum = numf / nums;
cout << Divide; //And here
//
}
| |
Other than that I don't see any errors, only that at some places your code can be improved, like using the
+=
operator and using
switch
instead of
if
s. But where is your code that outputs the result as a roman numeral? Do you have problem figuring that out?
P.S. You should use
std::string
instead of c-strings whenever available. What if the user inputted a roman numeral that has more than 20 chars? It would probably cause a memory corruption or something like that and crash your program. But
std::string
would allocate more memory from the heap for you, so that you don't have to worry about anything.