Thanks all for your help, I've condensed the decleration of the arrays down a bit, and added in support for 4's and 9's, which I realised actually fits in with the current way the program runs, only the arrays needed to be extended. Program now works almost perfectly, except when you put in 9 for instance, it prints the "IX", but then follows it with a "V", asif its continuing some loop somewhere. For the life of me Ive no idea why.... ??
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int checkint(char s[]) //Checks if string is purely numerical
{
int t = 1; // Set t=1
int length = strlen(s); // Define string length
for (int i = 0; i < length; i++) // For each character
{
if (s[i] >= '0' && s[i] <= '9'); // If numerical, then do nothing
else t = 0; //If not, then set t=0
}
return t;
}
static void roman(int n)
{
char r[13][2] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int t[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
int i[13];
for (int a = 0; a < 13; a++)
{
if (n >= t[a])
{
i[a] = n / t[a];
n = n - i[a]*t[a];
for (int b = 0; b < i[a]; b++)
printf("%s", r[a]);
}
else;
}
printf("\n");
}
int main(int argc, char *argv[])
{
if(argc < 2) // Error is number of arguments is less than 2
{
fprintf(stderr, "%s: program expected 1 or more arguments, but received %d\n", argv[0], argc-1);
exit(EXIT_FAILURE);
}
else
{
// Loop for each argument passed to the program
for(int i = 1; i < argc; i++)
{
if (!checkint(argv[i])) // Check arguments provided are numerical
{ // If not, then exit and give error message
fprintf(stderr, "%s: program expected positive numerical arguments\n", argv[0]);
exit(EXIT_FAILURE);
}
else
{
int n = atoi(argv[i]); // Argument as integer
roman(n); // Call roman function
}
}
// Exit indicating success
exit(EXIT_SUCCESS);
}
return 0;
}