Not sure if this counts as one question or four, as it has four parts, if so ple
ID: 3807680 • Letter: N
Question
Not sure if this counts as one question or four, as it has four parts, if so please do a level and ill repost the next thanks, let me know
The program should read from standard input and write to standard output. Input will consist of a series of lines each containing a number to be converted. For each input line, the program should write a line of output that consists of the converted number terminated with a newline. The program should continuously read input and write output until all input is processedExplanation / Answer
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
string singleRoman[10] = {"", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"};
// This function returns value of a Roman symbol
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
// Returns Arabic value of roman numeral
int romanToArabic(string &str)
{
// convert string to upper case
transform(str.begin(), str.end(), str.begin(), ::toupper);
// Initialize result
int res = 0;
// Traverse given input
for (int i=0; i<str.length(); i++)
{
// Getting value of symbol s[i]
int s1 = value(str[i]);
if (i+1 < str.length())
{
// Getting value of symbol s[i+1]
int s2 = value(str[i+1]);
// Comparing both values
if (s1 >= s2)
{
// Value of current symbol is greater
// or equal to the next symbol
res = res + s1;
}
else
{
res = res + s2 - s1;
i++; // Value of current symbol is
// less than the next symbol
}
}
else
{
res = res + s1;
i++;
}
}
return res;
}
int main()
{
string roman;
while(getline(cin, roman))
{
cout << "Roman : " << roman << " Arabic: " << romanToArabic(roman) << endl;
}
return 0;
}
// This do level1 and level2 completely. For level 3 it is coverting all valid number but is not handling invalid chacrters.
Hope it helps.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.