Exceptions in C++
Tasks
//csc232.h
#ifndef CSC232_LAB07_H #define CSC232_LAB07_H #define FALSE 0 #define TRUE 1 #define EXECUTE_BLOCK TRUE // TODO: When you create your pull request, make sure all of the following are set to TRUE #define TEST_INVALID_TARGET_EXCEPTION FALSE #define TEST_UNEXPECTED_ERROR_EXCEPTION FALSE #define TEST_INVALID_RANGE_EXCEPTION FALSE #include <stdexcept> #include <string> /** * @brief Custom exception to be thrown whenever a logical error is encountered. */ class TargetNotFoundException : public std::logic_error { public: /** * @brief Initializing constructor. * @param message an informative message to include with this logic_error */ explicit TargetNotFoundException(const std::string &message = "") : std::logic_error("Target not found: " + message) { // Intentionally empty as initialization utilizes an initializer list } }; // TODO: Create a custom exception class named InvalidTargetException that extends std::invalid_argument // TODO: Create a custom exception class named UnexpectedErrorException that extends std::runtime_error // TODO: Create a custom exception class named InvalidRangeException that extends std::range_error /** * @brief A demonstration of throwing the TargetNotFoundException. * @param target the target that wasn't found during processing */ void ThrowTargetNotFoundException(const std::string& target) { throw TargetNotFoundException(target); } /** * @brief A demonstration of throwing the InvalidTargetException. * @param error the error encountered during processing */ void ThrowInvalidTargetException(const std::string& error) { // TODO: throw an InvalidTargetException with the given error message // TODO: when done, change TEST_INVALID_TARGET_EXCEPTION to TRUE and commit your changes } /** * @brief A demonstration of throwing the UnexpectedErrorException. * @param error the error encountered during processing */ void ThrowUnexpectedErrorException(const std::string& error) { // TODO: throw an UnexpectedErrorException with the given error message // TODO: when done, change TEST_UNEXPECTED_ERROR_EXCEPTION to TRUE and commit your changes } /** * @brief A demonstration of throwing the InvalidRangeException. * @param error the error encountered during processing */ void ThrowInvalidRangeException(const std::string& error) { // TODO: throw an InvalidRangeException with the given error message // TODO: when done, change TEST_INVALID_RANGE_EXCEPTION to TRUE and commit your changes } #endif //CSC232_LAB07_H
//main.cpp
#include <cstdlib> #include <iostream> #include <string> #include "csc232.h" /** * @brief A contrived function that always throws an exception * @param target presumably something this function seeks to find * @return true * @throws ThrowTargetNotFoundException always! */ bool findSomeTarget(const std::string& target) { ThrowTargetNotFoundException(target); return true; } /** * @brief A simple demonstration on how to handle exceptions and gracefully exit. * @return EXIT_SUCCESS upon successfully handling exceptional code. */ int main() { std::cout << "A program doomed to failure..." << std::endl << std::endl; bool targetDoesNotExist{false}; std::string target; // TODO: Run this main target with EXECUTE_BLOCK initially set to true and observe the exit code #if EXECUTE_BLOCK std::cout << "Enter a target value to search: "; std::cin >> target; targetDoesNotExist = findSomeTarget(target); #else // TODO: Toggle EXECUTE_BLOCK to false, run this target again and observe the exit code try { std::cout << "Enter a target value to search: "; std::cin >> target; targetDoesNotExist = findSomeTarget(target); } catch (const TargetNotFoundException& notFoundException) { std::cerr << notFoundException.what() << std::endl; targetDoesNotExist = true; } if (targetDoesNotExist) { std::cout << "I told you so... this program was doomed to fail!" << std::endl; std::cout << "But at least it did so gracefully ;-)" << std::endl << std::endl; } #endif return EXIT_SUCCESS;
In: Computer Science
Write down the truth table fora 4-to-2 priority encoderhaving input W[3:0]and with priority levels in the decreasing order (i.e., W[0]-Highest, ....., W[3]-Least). Write down the Verilog code for implementing the same.
plz asap fast
In: Computer Science
C++
Add a function that finds & displays all the words that begin with the letter 's'.
The text file "dickens.txt" is as follows:
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair...
Display this at the end of the program which should look like this:
WORDS THAT BEGIN WITH 'S': season, spring
"spring" appears twice, duplicate works should only appear once.
The code is as follows:
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
multiset<string> display_and_load_words(string
filename);
set<string> get_unique_words(multiset<string>&
words);
int main() {
cout << "The Word Counter program\n\n";
string filename = "dickens.txt";
cout << "FILE TEXT: ";
auto words = display_and_load_words(filename);
cout << "WORD COUNT: " << words.size()
<< endl << endl;
auto unique_words = get_unique_words(words);
cout << unique_words.size() << " UNIQUE WORDS:
";
for (string word : unique_words) {
cout << word << '
';
}
cout << endl << endl;
cout << "COUNT PER WORD: ";
for (string word : unique_words) {
cout << word << '='
<< words.count(word) << ' ';
}
cout << endl << endl;
}
multiset<string> display_and_load_words(string filename)
{
multiset<string> words;
ifstream infile(filename);
if (infile) {
string word;
while (infile >> word) {
cout <<
word << ' ';
string new_word = "";
for (char c : word) {
if (c == '.' || c == ',') {
continue;
}
else if (isupper(c)) {
new_word += tolower(c);
}
else {
new_word += c;
}
}
words.insert(new_word);
}
cout << endl <<
endl;
infile.close();
}
return words;
}
set<string> get_unique_words(multiset<string>&
words) {
set<string> unique_words;
for (string word : words) {
auto search =
unique_words.find(word);
if (search == unique_words.end())
{
unique_words.insert(word);
}
}
return unique_words;
}
In: Computer Science
I need to write a function that takes a user-provided string like 1-3-5, and output a corresponding series of letters, where A is assigned to 1, B is assigned to 2, C is assigned to 3, etc. So in the case of 1-3-5 the output would be ACE. For 2-3-4, it should print BCD. For ?-3-4 or --3-4 it should still print BCD. **CANNOT USE LISTS, SETS, DICTS, ETC. CANNOT USE SPLIT FUNCTION. ** Here is the code I have written so far:
def num_to_let(encoded): result = "" start = 0 for char in range(len(encoded)): if encoded[char] == '-': i = encoded.index("-") sub_str = encoded[start:i] if not sub_str.isdigit(): result += "" else: letter = chr(64 + int(sub_str)) if 0 < int(sub_str) < 27: result += letter else: result += "" start += len(sub_str) + 1 print(start) return result print(num_to_let('4-3-25'))
It only outputs "D". Please let me know how I can correct this code.
In: Computer Science
Program #1: You will be writing code for several different examples of conditional execution. Each example should be written as a unique method. Each method should include a method header. So the basic outline of your code is: public class Branching { /** * This is an example method header. Notice how it's multi-line and written * using college-level English and not fragments - this is for the Human to * read and not the compiler to parse, so be verbose here. The purpose of this * main method is call the methods written for each of the parts of the *assignment. */ public static void main(String[] args) { methodA(); } public static void methodA() { /** *methodA header */ } A. Prompt the user with: "Enter a whole number". a. Determine if the number is negative and if so, print: "The number is negative." b. Determine if the number is positive and if so, print: "The number is positive." B. Ask the user for another whole number, and then determine if the number is even or odd. a. Hint: modulo might help. b. Print out a message that includes the number the user input as well as indicating if the number the user input was odd or even. C. Ask the user for a temperature, stored as an integer. Write an if/else statement that asks: Is the temperature higher than 78 degrees? If it is not, is the temperature less than (or equal to) 78 degrees? a. Describe the current temperature as “higher than 78 degrees” or “less than or equal to 78 degrees” D. Prompt the user for a letter grade and store this in a char. Then, write a multi-way if statement that ends in a tail-test, that asks the following questions: Is the grade an “A”? Else is the grade a “B”? Else is the grade a “C”? Else is the grade a “D”? Else is the grade an “F”? a. Notice the use of the word else in the sentence above, which provides for a more precise meaning. In spoken English we might use the word “or” instead, but of course, English is terribly ambiguous and Java needs to be discrete, deterministic, and precise. E. Rewrite your code for number D, but use a switch statement to accomplish the same thing. F. Prompt the user for two integer values and store them as “firstInteger” and “secondInteger”. a. Write an if/else statement that outputs either: “ firstInteger was larger than secondInteger” or “secondInteger was larger than firstInteger” on the console, based on the values provided by user that also includes the integer values in the output stament. b. If the values are equal, indicate this in an output that includes the values of the integers.
In: Computer Science
PROGAMMING LANGUAGE: C++
Can anyone solve this assignment? Especially the extra credit part? Thanks.
Please study the code 'Stack as Array example ' posted below.
You need to implement a stack template, but this time implement the stack as a single linked list. The test of the class should be done with the same main function, slightly modified to declare a stack object and properly call the class functions.
There is a helper file in the module that shows you a sample definition of a template class. This is just an example, you do not need to implement all functionality. You could implement all functions for 5 points extra credit. If you chose to implement the additional functions, you should test them all in the driver ( main ) function.
***************************************************************************************************************
/**
* Stack implementation using array in C/procedural language.
*/
#include
#include
#include
//#include // For INT_MIN
#define SIZE 100
using namespace std;
/// Create a stack with capacity of 100 elements
int stack[SIZE];
/// Initially stack is empty
int top = -1;
/** Function declaration to perform push and pop on stack */
void push(int element);
int pop();
void display();
int main()
{
int choice, data;
while(1)
{
/* Menu */
cout <<"------------------------------------\n";
cout <<" STACK IMPLEMENTATION PROGRAM \n";
cout <<"------------------------------------\n";
cout <<"1. Push\n";
cout <<"2. Pop\n";
cout <<"3. Size\n";
cout <<"4. Print Stack\n";
cout <<"5. Exit\n";
cout <<"------------------------------------\n";
cout <<"Enter your choice: ";
cin >>choice;
switch(choice)
{
case 1:
cout <<"Enter data to push into stack: ";
cin >> data;
// Push element to stack
push(data);
break;
case 2:
data = pop();
/// If stack is not empty
if (data != INT_MIN)
cout <<"Data => " << data << endl;
break;
case 3:
cout <<"Stack size: " << top + 1 << endl;
break;
case 4:
display();
break;
case 5:
cout <<"Exiting from app.\n";
exit(0);
break;
default:
cout <<"Invalid choice, please try again.\n";
}
cout <<"\n\n";
}
return 0;
}
/**
* Function to push a new element in stack.
*/
void push(int element)
{
/// Check stack overflow
if (top >= SIZE)
{
cout <<"Stack Overflow, can't add more element element to
stack.\n";
return;
}
/// Increase element count in stack
top++;
/// Push element in stack
stack[top] = element;
cout <<"Data pushed to stack.\n";
}
/**
* Function to pop element from top of stack.
*/
int pop()
{
/// Check stack underflow
if (top < 0)
{
cout <<"Stack is empty.\n";
/// Throw empty stack error/exception
/// Since C does not have concept of exception
/// Hence return minimum integer value as error value
/// Later in code check if return value is INT_MIN, then
/// stack is empty
return INT_MIN;
}
/// Return stack top and decrease element count in stack
return stack[top--];
}
void display()
{
if ( top >=0)
{
for(int i = 0; i <= top ; i++ )
cout << stack[i] << " ";
cout << endl;
}
else
cout << "stack is empty\n\n";
}
And here is the "helper file in the module" the teacher gave us:
Assignmenmt 06 HELP -- Stack Class Template Definition
Assignment help -- linked list stack sample header file
//Header File: linkedStack.h
#ifndef H_StackType
#define H_StackType
#include
#include
using namespace std;
//Definition of the node
template
struct nodeType
{
Type info;
nodeType *link;
};
template
class linkedStackType:
{
public:
//Overload the assignment operator.
const linkedStackType& operator=
(const linkedStackType&);
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty;
// otherwise returns false.
bool isEmptyStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns false.
bool isFullStack() const;
//Function to initialize the stack to an empty state.
//Postcondition: The stack elements are removed;
// stackTop = nullptr;
void initializeStack();
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem
// is added to the top of the stack.
void push(const Type& newItem);
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top
// element of the stack is returned.
Type top() const;
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
void pop();
//Default constructor
//Postcondition: stackTop = nullptr;
linkedStackType();
//Copy constructor
linkedStackType(const linkedStackType& otherStack);
~linkedStackType();
//Destructor
//Postcondition: All the elements of the stack are
// removed from the stack.
private:
nodeType *stackTop; //pointer to the stack
void copyStack(const linkedStackType& otherStack);
//Function to make a copy of otherStack.
//Postcondition: A copy of otherStack is created and
// assigned to this stack.
};
In: Computer Science
A) Many test cases.
For each case, the first line is the number N that indicates the amount of the students in the database.
Next to several N lines are the information of each student, include student ID, name, gender, and age.
And then will receive a number M that indicates there will be M search.
For each search line is an ID number, you need to compare to the database if there is any student with that ID. If yes, print ID, name, gender, and age of this student (if the ID is repeated, just print the previous one); if not, print "No Answer!".
You need to do this question by defining the data structure otherwise you can't real get the points.
Note: need can accept Chinese word! (take care of your array size)
Sample Input
4
1 Anna G 22
2 Teddy B 19
3 Joseph B 21
4 Rita G 22
2
1
5
2
20 阿王 男 16
23 阿美 女 15
1
23
Sample Output
1 Anna G 22
No Answer!
23 阿美 女 15
B)
Use stack to implement postfix arithmetic operation.
Input
Many test cases until EOF.
Each line is a postfix arithmetic operation formula.
There is no blank between the numbers, and the number only is 0-9.
Output
The result of each line.
But if the postfix arithmetic operation formula is wrong (it means you can't get the correct answer), please output "Input Error".
Sample Input
35+
3+5
63/14-*3+8-
Sample Output
8
Input Error
-11
C) There are several block stacks. The number of blocks for each stack may not be same, so your task is to move the block to let them be the same and calculate the minimum moves.
Example,
1 2 3
move stack 3 one block to the stack 1, so it will be:
2 2 2
Input
Many test cases.
For each case, first line is the number N(N<=50) of block stacks.
Next several N numbers are the number of blocks for each stack.
When N=0, the test is end.
Output
The case number and the minimum moves of each case. All the test are legal.
Sample Input
5
1 2 3 4 5
3
9 4 2
0
Sample Output
Set #1
The minimum number of moves is 3.
Set #2
The minimum number of moves is 4.
D)
Naming is important in the code. We always choose the relational vocabulary to name a variable. When we have two or more vocabularies to name, we are used to let the first letter of each vocabulary to be capitalized and connect all the vocabulary.
Take example, room number => RoomNuber sky color => SkyColor
Input
Many test cases until EOF.
Each line is many vocabularies.
Output
Naming result of each vocabulary.
Sample Input
aaaa bbbb cccc
ABCD BCDF FGHRTH
Sample Output
AaaaBbbbCccc
AbcdBcdfFghrth
Programming language: | C++ |
In: Computer Science
Objective:
Create a program that has a class to represent a cup of coffee that combines the properties: name and caffeine content. The class should also have a method that calculates the number of cups that would be maximally risky to consume in a short period of time. The program should create two instances of the class coffee where the user enters their properties and should output the amount of coffees that consumed would be risky.
Requirements:
Write a class called Coffee with the following
Next write a test class
In: Computer Science
1) Compare and contrast the OCSP and CRL approaches for certificate revocation.
2) What X.509 field does a browser check to determine if a received
certificate is allowed to be used for the site that sends it?
3) Why do certificates have an expiration date if there are other certificate revocation mechanisms (i.e. OCSP and CRL)?
In: Computer Science
Assume that you are working for a company that develops software systems for in-house use in its design of aircraft engines. Being a software engineer you may not have any expertise in aircraft engines. While testing programs for such applications, what are the challenges you are likely to face, and how will you overcome them?
In: Computer Science
Homework Description: Creating your own quiz
As you likely have noticed, if you retook an ICON reading quiz in this course, you most likely received a different set of questions. This is because the questions are randomly selected from a question bank of possible questions where the number of questions on the quiz is (usually) less than the number of questions in the question bank. In this homework assignment, you will write your own question bank of at least 10 quiz questions (they do not have to be related to programming) and will write a menu-based program with three options: (1) take quiz, (2) view question statistics, and (3) quit. If option (1) from the menu is selected, the user should be presented with a random subset of three of the questions from your question bank (note: you should take care to make sure that none of your questions are repeated). After each question is presented, the user will provide an answer before the program presents the next question. It is up to you how your program informs the user as to how many and/or which questions he/she got correct on the quiz (e.g., displaying a message at the end of each question and/or at the end of the quiz). If option (2) from the menu is selected, the program should display (based on all quizzes that have been taken while your program has been running), for each question, the number of times the question has been asked and the number of times the question has been correct. To display this information, the formatting is up to you, but one option would be to display a fraction x/yx/y where xx is the number of correct answers and yy is the number of times the question has been asked. You should also display each question as the user doesn’t know the order of the questions in the question bank. Your menu-based program should continue to run until the user selects option 3 (note, you should use a blocking-while loop, or something similar, to make sure that the user enters a valid choice of 1, 2, or 3.)
Implementation hints
In creating your question bank, it is recommended that you create two arrays: one array (of strings) to store the quiz questions and one array (of integers) to store the correct quiz answers. All of your quiz answers should consistently be of the same type and it is recommended that you use integers to store the quiz answers. For example, the following code illustrates creating a question bank with only two questions (remember that you need at least 10 questions):
string questions[] = {"How many days are in January?", "How many days are in February (non-leap year)?"}; int answers[] = { 31, // January 28 }; // February (non-leap year)
Note, since questions that ask how many days are in a month is provided as an example, you may NOT use this as the theme for your questions. Please be creative and come up with your own questions.(Note, also consider the possibility of multiple choice questions with integer options (e.g., 1, 2, 3, 4).)
In: Computer Science
Software Engineering question:
Give an example of two software engineering artifacts. One that you would place under configuration management and one that you would not. Justify your choices.
In: Computer Science
Doing the work on Linux in Putty:
You are to create a hard link to one of your existing files on someone else's directory (or vice versa). In other words, you know that you can link a file within your own directories, but you can also have a link to one of your files on other areas of the unix system as long as you have permissions to write to that directory (in this case, your partner).
Create a subdirectory called temp where you can place this temporary link. Remember that you do not link a file to another file. You create a hard link to an existing file. So, user A has file1 that he/she wants to give access to user B. User B has to open certain directory permissions, for this to happen, then User A can create the link on user B directory (user A NEVER goes to user B directories typing cd), but if permissions are opened correctly all the commands will be done from user A directory without shell error messages such as “can not access..”.
We cannot get the ln part to work. How do you share the hard link with the other user???
In: Computer Science
Please provide a detailed walk through osf this Java application, which uses recursion to find the maximal (largest) contiguous sum in a list of integers. Base code on the algorithm below.
Input Read from a text file (List.dat) lines of data where each line represents a list in this format:
list-size numbers in the list separated by blanks 4 100 -50 5 8
For example, List.dat might contain: 7 -2 -4 30 15 -7 -5 1000 2 -50 100 6 1000 -2000 900 2800 -2900 2801 0 4 100 -10 5 8 4 100 -50 5 8
Note: the list-size must be greater than 0. Bypass any line with 0 or a negative number as the first number, i.e., NO empty list. No error checking needed. You may assume that your input file is structured correctly: it contains all integers, and if the first number on a line is n, then there are n integers that follow it on that line.
Output For each line of data read, display the largest sum of consecutive integers in the list followed by the list itself. For the example lists as above, your output would be:
Largest sum of The list used consecutive integers 1033 -2 -4 30 15 -7 -5 1000 100 -50 100 3700 1000 -2000 900 2800 -2900 2801 103 100 -10 5 8 100 100 -50 5 8
Algorithm - processing
• Use a loop to read each line of data from List.dat until end-of-file is reached
• On each pass of the loop implement an array of list-size (1st number on the line) to hold the list of numbers read (from the rest of the line)
• Invoke a recursive method (or a surrogate/helper method that invokes a recursive method— more on this below) that returns the largest contiguous sum for this list
• Display the sum and the list (as above) • Do not use any "global" variables in your code (your methods should use only parameters or local variables, no static variables that recursive methods would refer to, as they would not be instantiated)
Input File Include a file of test data in your src folder. The contents of your file will be replaced with my test data. Recall you can access this file in your program with this code:
Scanner fileScan = new Scanner (new File("src\\List.dat"));
You can recall in CSC 135 we read from a file that contained URLs.
Using Recursion Your main method should call this helper method, which returns the maximum contiguous sum on the list aList:
//This method returns the maximum contiguous sum public static int maxSum(int[] aList)
but in order to use recursion we need more parameters, so the method above maxSum will simply serve as a surrogate which calls another method, the recursive method, which does all the work:
//This method returns the maximum contiguous sum from a list stored in an //array which begins at cell "start" and ends at cell "end" public static int maxContigSum (int[] aList, int start, int end)
Using the approach for developing a recursive solution:
• Base case: a list with 1 item. What will the maximum sum be? • Assume we can determine the maximum sum for a list of contiguous items in a shorter list. (Looking ahead: the shorter list that we'll use in the next step, the general case, will be the list beginning at cell "start+1" and ending at cell "end (you could also do "start" till "end-1"). We'll remember that sum as it will be a candidate for the maximum sum that our method should return. • General case: From our assumption we know what the maximum contiguous sum is for all cells excluding the first cell, so now we need to consider any sum, which contains the first cell. So now compute (use a loop, not recursion here) all possible sums from your list that include the first cell. As you compute these sums compare them to your maximum sum so far (which initially will be what was returned by your assumption above)
In: Computer Science
Python
Please debug each python block. Do not change the algorithm. You can add statements or you can modify existing python statements.
#2) The below code prints all numbers from 5 to 20. Modify the
below while loop to print odd numbers from 5 to 21,
# including 21. Correct syntax errors as well.
i = 5
while(i<21):
print(i)
i = i+1
In: Computer Science