Mikey - 1 year ago 82

C Question

Trying to implement a very simple Roman Numeral to Decimal converter but can't seem to figure out a way for the program to return -1 if any non-roman numeral characters are in the string. This is what I have so far.

`#include <stdio.h>`

#include <ctype.h>

int convertFromRoman(const char *s)

{

int i = 0;

int total = 0;

while (s[i] != '\0') {

if (isalpha(s[i]) == 0) {

return -1;

}

if (toupper(s[i]) == 'I') {

total += 1;

}

if (toupper(s[i]) == 'V') {

total += 5;

}

if (toupper(s[i]) == 'X') {

total += 10;

}

if (toupper(s[i]) == 'L') {

total += 50;

}

if (toupper(s[i]) == 'C') {

total += 100;

}

if (toupper(s[i]) == 'D') {

total += 500;

}

if (toupper(s[i]) == 'M') {

total += 1000;

} else {

return -1;

}

i++;

}

if (total == 0) {

return -1;

}

return total;

}

int main()

{

printf("%d\n", convertFromRoman("XVII"));

printf("%d\n", convertFromRoman("ABC"));

}

The first one should return 17 and the second one should return -1. However they both return -1 but if I remove the else statement, the first one returns 17 and the second one returns 100.

Any help is appreciated.

Answer Source

Change `if()`

`if()`

`if()`

`else`

to `if()`

`else if ()`

`else if()`

`else`

```
if (toupper(s[i]) == 'I') {
total += 1;
}
else if (toupper(s[i]) == 'V') {
total += 5;
}
else if (toupper(s[i]) == 'X') {
total += 10;
}
....
else if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
```