Question

Looking for help understanding how this example program flows and works. Can you write comments next...

Looking for help understanding how this example program flows and works. Can you write comments next to each line of code explaining what it does? Why does it use a switch? why not set the roman numerals as constants instead of a switch? Thank you!!

//CPP program for converting roman into integers

#include <iostream>
#include <fstream>
#include<cctype>
#include<cstdlib>
#include<string.h>
using namespace std;

int value(char roman)
{
switch(roman)
{
case 'I':return 1;
case 'V':return 5;
case 'X':return 10;
case 'L':return 50;
case 'C':return 100;
case 'D':return 500;
case 'M':return 1000;
default : return -1;
}
}


int get(const string& input)
{
int total=0; char prev='%';
for(int i=(input.length()-1); i>=0; i--)
{
if(value(input[i])==-1)
return -1;
if(value(input[i])<total && (input[i]!=prev))
{ total -= value(input[i]);
prev = input[i];
}
else
{
total += value(input[i]);
prev = input[i];
}
}
return total;
}


int main()
{
char str[255];
int val;
ifstream in("Roman.txt");

if(!in) {
cout << "Cannot open input file.\n";
return 1;
}

  

while(in) {
in.getline(str, 255); // delim defaults to '\n'
  
if(in)
{
val=get(str);
if(val==-1)
cout << "Invalid character"<<endl;
else
cout << str << " = "<<val<<endl;
  
}
  

}

in.close();

return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//CPP program for converting roman into integers
#include <iostream>
#include <fstream>
#include<cctype>
#include<cstdlib>
#include<string.h>
using namespace std;
// Takes a roman character as input, and will return its integer equivalent,
// given the input is a valid roman character, and returns -1 otherwise.
int value(char roman)
{
    switch(roman)
   {
       case 'I':return 1;       //If the input is: I, returns 1.
       case 'V':return 5;       //If the input is: V, returns 5.
       case 'X':return 10;       //If the input is: X, returns 10.
       case 'L':return 50;       //If the input is: L, returns 50.
       case 'C':return 100;   //If the input is: C, returns 100.  
       case 'D':return 500;   //If the input is: D, returns 500.
       case 'M':return 1000;   //If the input is: M, returns 1000.
       default : return -1;   //If neither of the above characters, returns -1.
   }
}

//Takes a roman number string as input, and returns its equivalent integer as output.
int get(const string& input)
{
   int total=0;   
   char prev='%';
   for(int i=(input.length()-1); i>=0; i--)   //From the last character in the input string, down till the first character.
   {
       if(value(input[i])==-1)   //If the character in the input string is not a valid roman literal.
           return -1;           //Return -1.
       if(value(input[i])<total && (input[i]!=prev)) //If the current literal value is less than tha total,
                               //and current literal is not same as the previous literal.
       {
          total -= value(input[i]);   //Subtract the current literal value, from the total.
           prev = input[i];           //Mark the current literal as prev, and move forward.
       }
       else                   //If that condition is not satisfied.
       {
           total += value(input[i]);   //Add the current literal value, to the total.
           prev = input[i];           //Mark the current literal as prev, and move forward.
       }
   }  
   return total;           //After the characters in string are exhausted, return the total value.
}

int main()
{
char str[255];           //Declares an array of characters.
int val;               //Declares an integer.
ifstream in("Roman.txt");   //Reads the file Roman.txt as input file stream.
if(!in) {       //If file is not opened successfully.
cout << "Cannot open input file.\n";   //Push a message to screen.
return 1;                   //And stop execution.
}
  
while(in) {       //Keep reading line by line of input from the file, till end of file is reached.
in.getline(str, 255); // delim defaults to '\n'  
  
if(in)               //If read value is not end of file.
{
val=get(str);   //Call the function get, which return the integer equivalent of roman string, and stores the returned value in val.
if(val==-1)       //If the read string is invalid.
cout << "Invalid character"<<endl;   //Show this message to screen.
else           //If valid.
cout << str << " = "<<val<<endl;   //Show the integer value to screen.
  
}
  
}
in.close();   //After reading all the strings from file, close the file.
return 0;   //Stop execution.
}

Add a comment
Know the answer?
Add Answer to:
Looking for help understanding how this example program flows and works. Can you write comments next...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str);...

    #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str); int numConsonants(char *str); int main() {    char string[100];    char inputChoice, choice[2];    int vowelTotal, consonantTotal;    //Input a string    cout << "Enter a string: " << endl;    cin.getline(string, 100);       do    {        //Displays the Menu        cout << "   (A) Count the number of vowels in the string"<<endl;        cout << "   (B) Count...

  • #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str);...

    #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str); int numConsonants(char *str); int main() {    char string[100];    char inputChoice, choice[2];    int vowelTotal, consonantTotal;    //Input a string    cout << "Enter a string: " << endl;    cin.getline(string, 100);       do    {        //Displays the Menu        cout << "   (A) Count the number of vowels in the string"<<endl;        cout << "   (B) Count...

  • // Write a program that determines how many of each type of vowel are in an...

    // Write a program that determines how many of each type of vowel are in an entered string of 50 characters or less. // The program should prompt the user for a string. // The program should then sequence through the string character by character (till it gets to the NULL character) and count how many of each type of vowel are in the string. // Vowels: a, e, i, o, u. // Output the entered string, how many of...

  • fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string>...

    fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; struct book { int ISBN; string Author; string Title; string publisher; int Quantity; double price; }; void choice1(book books[], int& size, int MAX_SIZE) { ifstream inFile; inFile.open("inventory.txt"); if (inFile.fail()) cout <<"file could not open"<<endl; string str;    while(inFile && size < MAX_SIZE) { getline(inFile, str); books[size].ISBN = atoi(str.c_str()); getline(inFile, books[size].Title);    getline(inFile, books[size].Author); getline(inFile, books[size].publisher);          getline(inFile,...

  • Can someone help with this C++ code. I am trying to compile and I keep running...

    Can someone help with this C++ code. I am trying to compile and I keep running into these 4 errors. #include <iostream> #include <cassert> #include <string> using namespace std; typedef int fsm_state; typedef char fsm_input; bool is_final_state(fsm_state state) { return (state == 3) ? true : false; } fsm_state get_start_state(void) { return 0; } fsm_state move(fsm_state state, fsm_input input) { // our alphabet includes only 'a' and 'b' if (input != 'a' && input != 'b') assert(0); switch (state) {...

  • This is C++ code for parking fee management program #include <iostream> #include <iomanip> using namespace std;...

    This is C++ code for parking fee management program #include <iostream> #include <iomanip> using namespace std; void input(char& car, int& ihour,int& imin, int& ohour, int& omin); void time(char car, int ihour, int imin, int ohour, int omin, int& phour, int& pmin, int& round, double& total); void parkingCharge (char car, int round, double& total); void print(char car, int ihour, int imin, int ohour, int omin, int phour, int pmin, int round, double total); int main() { char car; int ihour; int...

  • HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE...

    HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE 100 #define NO_ELEMENT -999999 using namespace std; class Stack { int arr[SIZE]; // array to store Stack elements int top; public: Stack() { top = -1; } void push(int); // push an element into Stack int pop(); // pop the top element from Stack int topElement(); // get the top element void display(); // display Stack elements from top to bottom }; void Stack...

  • I'm having trouble getting a certain output with my program Here's my output: Please input a...

    I'm having trouble getting a certain output with my program Here's my output: Please input a value in Roman numeral or EXIT or quit: MM MM = 2000 Please input a value in Roman numeral or EXIT or quit: mxvi Illegal Characters. Please input a value in Roman numeral or EXIT or quit: MXVI MXVI = 969 Please input a value in Roman numeral or EXIT or quit: EXIT Illegal Characters. Here's my desired output: Please input a value in...

  • Need help with a C++ program. I have been getting the error "this function or variable...

    Need help with a C++ program. I have been getting the error "this function or variable may be unsafe" as well as one that says I must "return a value" any help we be greatly appreciated. I have been working on this project for about 2 hours. #include <iostream> #include <string> using namespace std; int average(int a[]) {    // average function , declaring variable    int i;    char str[40];    float avg = 0;    // iterating in...

  • can you please split this program into .h and .cpp file #include <iostream> #include<string> #include<fstream> #define...

    can you please split this program into .h and .cpp file #include <iostream> #include<string> #include<fstream> #define SIZE 100 using namespace std; //declare struct struct word_block {    std::string word;    int count; }; int getIndex(word_block arr[], int n, string s); int main(int argc, char **argv) {    string filename="input.txt";    //declare array of struct word_block    word_block arr[SIZE];    int count = 0;    if (argc < 2)    {        cout << "Usage: " << argv[0] << "...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT