Question

In: Computer Science

IN C++ PLEASE. Use ONLY: exception handling, read and write files, arrays, vectors, functions, headers and...

IN C++ PLEASE. Use ONLY: exception handling, read and write files, arrays, vectors, functions, headers and other files, loops, conditionals, data types, assignment.  

  1. Calculating fuel economy. This program will use exceptions and stream errors to make a robust application that gets the number of miles and gallons each time the user fuels their car. It will put those values into vectors. Once the user wants to quit enter values, it will calculate the fuel economy.
    1. Create GetMiles() function that returns double.
      1. If there is a stream error, then throw a runtime_error with the message Invalid input received, you must enter a decimal number. Don’t forget to clear the error and ignore all characters until the end of the stream.
      2. If the value is less then or equal to zero, then throw a runtime_error with the message. Miles cannot be less than 0.
      3. Otherwise, return the miles the user entered
    2. Create GetGallons() function that returns double.
      1. If there is a stream error, then throw a runtime_error with the message Invalid input received, you must enter a decimal number. Don’t forget to clear the error and ignore all characters until the end of the stream.
      2. If the value is less than or equal to zero, then throw a runtime_error with the message. Gallons cannot be less than 0.
      3. Otherwise, return the miles the user entered
    3. Create GetMPG(vector<double miles, vector<double> gallons) function that returns a double.
      1. If the size of the vectors is 0, then throw a runtime_error with the message No values recorded MPG is nan
      2. Otherwise, total the miles and gallons and return the miles per gallon.
    4. The main program should loop and get the Gallons and Miles catching any exceptions that were thrown. Then ask if they want to enter another tank. If they enter gallons and miles put the values into the vectors given. When the user is done the program should calculate the MPG by calling GetMPG, catching the exception if the user did not enter any values. Then it should show the result.

Stream Errors

   cout << "Enter a number: " << endl;

   cin >> number;

  

   if (cin.fail()) {

      // Clear error state

      cin.clear();

      // Ignore characters in stream until newline

      cin.ignore(numeric_limits<streamsize>::max(), '\n');

      cout << "There was an error: " << endl;

     

   }

Throwing Errors

        throw runtime_error("Invalid value.");

Catching Errors

      try {
         // Code to try
      }
      catch (runtime_error &excpt) {
         // Prints the error message passed by throw statement
         cout << excpt.what() << endl;
      }

Make sure you include stdexcept and vector as well as the other standard modules.

Solutions

Expert Solution

// C++ program to calculate Fuel Economy

#include <iostream>
#include <stdexcept>
#include <limits>
using namespace std;

// function declaration
double GetMiles();
double GetGallons();
double GetMPG(vector<double> miles, vector<double> gallons);

int main()
{
vector<double> miles, gallons;
double in_miles, in_gallons;
char res;

// loop to input the miles and gallons and insert it into the vectors till the user wants
do
{
try
{
// input miles and gallons
in_miles = GetMiles();
in_gallons = GetGallons();
// insert the input into vectors
miles.push_back(in_miles);
gallons.push_back(in_gallons);
}catch(runtime_error &e)
{
// catch any exception raised
cout<<e.what()<<endl;
}
// ask if the user wants to enter another data
cout<<"Do you want to enter another tank (y/n)? ";
cin>>res;
}while(res == 'y' || res == 'Y');

// calculate and display the MPG
try{
cout<<endl<<"MPG: "<<GetMPG(miles, gallons);
}catch(runtime_error &e)
{
cout<<e.what()<<endl;
}
return 0;
}


// function that inputs miles from user and return it
double GetMiles()
{
double miles;
// input miles
cout<<"Enter the miles: ";
cin>>miles;
// check if there is any stream error
if(cin.fail())
{
cin.clear(); // clear the error
cin.ignore(numeric_limits<streamsize>::max(),'\n'); // ignore the characters until the end of line
throw runtime_error("Invalid input received, you must enter a decimal number.");
}else if(miles <= 0) // check if miles is less than or equal to 0
throw runtime_error("Miles cannot be less than 0");

return miles;
}

// function that inputs gallons from user and return it
double GetGallons()
{
double gallons;
// input gallons
cout<<"Enter the gallons: ";
cin>>gallons;
// check if there is any stream error
if(cin.fail())
{
cin.clear(); // clear the error
cin.ignore(numeric_limits<streamsize>::max(),'\n'); // ignore the characters until the end of line
throw runtime_error("Invalid input received, you must enter a decimal number.");
}else if(gallons <= 0) // check if gallons is less than or equal to 0
throw runtime_error("Gallons cannot be less than 0");

return gallons;
}

// function to calculate and return the miles per gallon (MPG)
double GetMPG(vector<double> miles, vector<double> gallons)
{
// check if the vectors contain any value
if(miles.size() == 0)
{
throw runtime_error("No values recorded MPG is nan");
}

// calculate the total miles and total gallons
double total_miles =0 , total_gallons = 0;
for(size_t i=0;i<miles.size();i++)
{
total_miles += miles[i];
total_gallons += gallons[i];
}
// calculate and return the MPG
return total_miles/total_gallons;
}

// end of program

Output:


Related Solutions

Objectives:  Write classes in C++  Use dynamic arrays  Write and read from files...
Objectives:  Write classes in C++  Use dynamic arrays  Write and read from files 1. WriteaclassGradeBookcontainingthefollowing: Private attributes: - courseName: a string representing the name of the course. - nbOfStudents: an integer representing the number of students enrolled in the course. The number of students is greater than or equal to 5. - grades: a double dimensional array of integers representing the grades of Test1, Test2 and Final of every student. It should be a dynamic array. Public...
In Python This assignment involves the use of text files, lists, and exception handling and is...
In Python This assignment involves the use of text files, lists, and exception handling and is a continuation of the baby file assignment. You should now have two files … one called boynames2014.txt and one called girlnames2014.txt - each containing the top 100 names for each gender from 2014. Write a program which allows the user to search your files for a boy or girl name and display where that name ranked in 2014. For example … >>>   Enter gender...
This assignment involves the use of text files, lists, and exception handling and is a continuation...
This assignment involves the use of text files, lists, and exception handling and is a continuation of the baby file assignment. You should now have two files … one called boynames2014.txt and one called girlnames2014.txt - each containing the top 100 names for each gender from 2014. Write a program which allows the user to search your files for a boy or girl name and display where that name ranked in 2014. For example … >>> Enter gender (boy/girl): boy...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with //comments . Please include a screen shot of the output Part 4: Calorie Counting Specifications: Write a program that allows the user to enter the number of calories consumed per day. Store these calories in an integer vector. The user should be prompted to enter the calories over the course of one week (7 days). Your program should display the total calories consumed over...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with //comments . Please include a screen shot of the output Part 1: Largest and Smallest Vector Values Specifications: Write a program that generates 10 random integers between 50 and 100 (inclusive) and puts them into a vector. The program should display the largest and smallest values stored in the vector. Create 3 functions in addition to your main function. One function should generate the...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a  ...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to   be   thrown   when   a   string   is   discovered   that   has   too   many   characters   in   it. Consider   a   program   that   takes   in   the   last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,  ...
Write a C++ app to read both files, store them into parallel vectors, sort the list...
Write a C++ app to read both files, store them into parallel vectors, sort the list of people in alphabetical order, display the new sorted list of names with their corresponding descriptions. Use the Bubble Sort strategy to rearrange the vector(s). File 1: Marilyn Monroe Abraham Lincoln Nelson Mandela John F. Kennedy Martin Luther King Queen Elizabeth II Winston Churchill Donald Trump Bill Gates Muhammad Ali Mahatma Gandhi Margaret Thatcher Mother Teresa Christopher Columbus Charles Darwin Elvis Presley Albert Einstein...
in C#, What is an exception and what are the advantages of exception handling?
in C#, What is an exception and what are the advantages of exception handling? What are the differences between the traditional error-handling methods and the object-oriented exception-handling methods and when should you use each one? Provide three to four paragraphs detailing your findings/views on these questions..provide examples with a simple code also..
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
Please write code for C language Problem: Write a couple of functions to process arrays. Note...
Please write code for C language Problem: Write a couple of functions to process arrays. Note that from the description of the function you have to identify what would be the return type and what would be part of the parameter. display(): The function takes an int array and it’s size and prints the data in the array. sumArray(): It takes an int array and size, and returns the sum of the elements of the array. findMax(): It takes an...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT