Write a program in C language. here\'s a program that needs to be fixed. We woul
ID: 644777 • Letter: W
Question
Write a program in C language. here's a program that needs to be fixed.
We would like the program to be tolerent of white space (spaces and tabs, and still provide the result if all of the other characters are valid roman digits.
If the user enters invalid characters, we would like the function to return 0 as a special value indicating an error instead of a partial result so far. We can use 0 as a special value because there is no Roman number representation for 0 (the Romans didn't understand 0) so 0 would not be returned for normal input. The driver should print an error message when this occurs and let the user try entering another number. You may modify any of the files that you need to, but you will need to break the link and copy the file for those you want to change.
#include <stdio.h>
#include "roman.h"
#include "romanutil.h"
int get_roman(void)
/* This function reads the next number in roman numerals from the input
* and returns it as an integer */
{ char rdigit;
int num = 0;
int dig_value, last_dig_value = M;
/* get the first digit */
rdigit = getchar();
/* while it is a roman digit */
while( is_roman(rdigit))
{
/* convert roman digit to its value */
dig_value = convert_roman(rdigit);
/* if previous digit was a prefix digit */
if(dig_value > last_dig_value)
/* adjust total */
num = num - 2 * last_dig_value + dig_value;
/* otherwise accumulate the total */
else num = num + dig_value;
/* save this digit as previous */
last_dig_value = dig_value;
/* get next digit */
rdigit = getchar();
}
/* return EOF if detected */
if(rdigit == EOF) return EOF;
/* return the number */
return num;
}
Explanation / Answer
#include <stdio.h>
#include "roman.h"
#include "romanutil.h"
int get_roman(void)
/* This function reads the next number in roman numerals from the input
* and returns it as an integer */
{ char rdigit;
int num = 0;
int dig_value, last_dig_value = M;
/* get the first digit */
rdigit = getchar();
/* while it is a roman digit */
while( is_roman(rdigit))
{
/* convert roman digit to its value */
dig_value = convert_roman(rdigit);
/* if previous digit was a prefix digit */
if(dig_value > last_dig_value)
/* adjust total */
num = num - 2 * last_dig_value + dig_value;
/* otherwise accumulate the total */
else num = num + dig_value;
/* save this digit as previous */
last_dig_value = dig_value;
/* get next digit */
rdigit = getchar();
}
/* 0 as input */
while(! is_roman(rdigit))
{ return 0;
printf("Invalid input!. Please enter a valid input");
rdigit=getchar();
}
/* return EOF if detected */
if(rdigit == EOF) return EOF;
/* return the number */
return num;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.