Roman numeral converter problem
First off I am quite new to programing so the solution is probably quite obvious (ether that or I wrote this program horribly wrong), so bear with me here. I am trying to make a program that converts Roman numerals to Arabic ones and it isn't doing what I thought it would. When I input, for example, "VII" it comes back with something like -2 million!?! BTW the comments are what I think the program does, not necessarily what it actually does. Thanks in advance. :D
Code:
#include <stdio.h> /*BEWARE!! THIS DOES NOT WORK YET*/
#include <string.h>
#include <stdlib.h>
void stoupper(char *s) /*definition for string upercase conversion*/
{
for(; *s; s++)
if(('a' <= *s) && (*s <= 'z'))
*s = 'A' + (*s - 'a');
}
char rome[20];
int arab=0;
int lngth;
int count;
int main()
{
fgets(rome, 20, stdin); /*gets the roman numeral*/
stoupper(rome); /*puts roman numeral in uppercase*/
lngth=strlen(rome); /*finds length of numeral*/
printf("You entered %s\n",rome);
printf("that is %d charicters long.\n", lngth-1);
int buf[lngth]; /*for adding up numbers that equal eachother*/
int lyr[lngth]; /*for the final tally*/
for(count=0; count<lngth; count++) /*puts a number value to each letter*/
{
switch(rome[count])
{
case 'M':
buf[count]=1000;
break;
case 'D':
buf[count]=500;
break;
case 'C':
buf[count]=100;
break;
case 'L':
buf[count]=50;
break;
case 'X':
buf[count]=10;
break;
case 'V':
buf[count]=5;
break;
case 'I':
buf[count]=1;
break;
default:
break;
}
}
int t=0;
for(count=0; count<lngth; count++) /* adds up numbers that are the same and moves them to a new aray*/
{
if(buf[count]==buf[count+1])
{
lyr[t]=buf[count]*2;
t++;
count++;
}
if(buf[count]==buf[count+1] && buf[count]==buf[count+2])
{
lyr[t]=buf[count]*3;
t++;
count=count+2;
}
else
{
lyr[t]=buf[count];
t++;
}
}
for(count=0; count<=t; count++) /* finds groups that subtract from the total */
{
if(lyr[count]<lyr[count+1])
{
lyr[count]=lyr[count]*-1;
}
}
for(count=0; count<t; count++) /*gets final sum */
{
arab=arab+lyr[count];
}
printf("In arabic:-%d", arab);
}