Question
Write the interface (.h file) of a class GasTank containing:
A data member named amount of type double.
A data member named capacity of type double.
A constructor that accepts a parameter of type double.
A function named addGas that accepts a parameter of type double and returns no value.
A function named useGas that accepts a parameter of type double and returns no value.
A function named isEmpty that accepts no parameters and returns a boolean value.
A function named isFull that accepts no parameters and returns a boolean value.
A function named getGasLevel that accepts no parameters and returns a double.
A function named fillUp that accepts no parameters and returns a double.
Solution
class GasTank
{
private:
double amount;
double capacity;
public:
GasTank(double);
void addGas(double);
void useGas(double);
bool isEmpty();
bool isFull();
double getGasLevel();
double fillUp();
};
Answers for C++ Course using "Starting out with C++ : from control structures through objects" by Tony Gaddis. 7/8th ed. I used the Pearson myprogramminglab to complete the homework. Here are my solutions/answers for the exercises/labs so please use the test bank as a GUIDE if you're stuck. Let me know if you find a better solution to a problem or any of the programming challenges. Thanks in advance for your support! Send in missing programming challenges to cplusplus.answers@gmail.com
13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10889
Question
Write the implementation (.cpp file) of the Averager class of the previous exercise. The full specification of the class is:
An data member named sum of type integer.
An data member named count of type integer.
A constructor with no parameters. The constructor initializes the data members sum and the data member count to 0.
A function named getSum that accepts no parameters and returns an integer. getSum returns the value of sum .
A function named add that accepts an integer parameter and returns no value. add increases the value of sum by the value of the parameter, and increments the value of count by one.
A function named getCount that accepts no parameters and returns an integer. getCount returns the value of the count data member, that is, the number of values added to sum .
A function named getAverage that accepts no parameters and returns a double. getAverage returns the average of the values added to sum . The value returned should be a value of type double (and therefore you must cast the data members to double prior to performing the division).
Solution
Averager::Averager()
{
sum=0;
count=0;
}
int Averager::getSum()
{
return sum;
}
void Averager::add(int theNum)
{
sum+=theNum;
count++;
}
int Averager::getCount()
{
return count;
}
double Averager::getAverage()
{
return (double) sum / (double) count;
}
Write the implementation (.cpp file) of the Averager class of the previous exercise. The full specification of the class is:
An data member named sum of type integer.
An data member named count of type integer.
A constructor with no parameters. The constructor initializes the data members sum and the data member count to 0.
A function named getSum that accepts no parameters and returns an integer. getSum returns the value of sum .
A function named add that accepts an integer parameter and returns no value. add increases the value of sum by the value of the parameter, and increments the value of count by one.
A function named getCount that accepts no parameters and returns an integer. getCount returns the value of the count data member, that is, the number of values added to sum .
A function named getAverage that accepts no parameters and returns a double. getAverage returns the average of the values added to sum . The value returned should be a value of type double (and therefore you must cast the data members to double prior to performing the division).
Solution
Averager::Averager()
{
sum=0;
count=0;
}
int Averager::getSum()
{
return sum;
}
void Averager::add(int theNum)
{
sum+=theNum;
count++;
}
int Averager::getCount()
{
return count;
}
double Averager::getAverage()
{
return (double) sum / (double) count;
}
Exericse Number
10889
13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10885
Question
Write the implementation (.cpp file) of the Accumulator class of the previous exercise. The full specification of the class is:
An data member named sum of type integer.
A constructor that accepts no parameters. The constructor initializes the data member sum to 0.
A function named getSum that accepts no parameters and returns an integer. getSum returns the value of sum .
A function named add that accepts an integer parameter and returns no value. add increases the value of sum by the value of the parameter.
Solution
Accumulator::Accumulator()
{
sum=0;
}
int Accumulator::getSum()
{
return sum;
}
void Accumulator::add(int theNum)
{
sum+=theNum;
}
Write the implementation (.cpp file) of the Accumulator class of the previous exercise. The full specification of the class is:
An data member named sum of type integer.
A constructor that accepts no parameters. The constructor initializes the data member sum to 0.
A function named getSum that accepts no parameters and returns an integer. getSum returns the value of sum .
A function named add that accepts an integer parameter and returns no value. add increases the value of sum by the value of the parameter.
Solution
Accumulator::Accumulator()
{
sum=0;
}
int Accumulator::getSum()
{
return sum;
}
void Accumulator::add(int theNum)
{
sum+=theNum;
}
Exericse Number
10885
13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10877
Question
Write the implementation (.cpp file) of the Counter class of the previous exercise. The full specification of the class is:
A data member counter of type int .
An data member named limit of type int .
A static int data member named nCounters which is initialized to 0 .
A constructor that takes two int arguments and assigns the first one to counter and the second one to limit . It also adds one to the static variable nCounters
A function called increment that accepts no parameters and returns no value. If the data member counter is less than limit , increment just adds one to the instance variable counter .
A function called decrement that accepts no parameters and returns no value. If counter is greater than zero, decrement subtracts one from the counter .
A function called getValue that accepts no parameters. It returns the value of the instance variable counter .
A static function named getNCounters that accepts no parameters and return an int . getNCounters returns the value of the static variable nCounters .
Solution
int Counter::nCounters = 0;
Counter::Counter(int theCounter, int theLimit)
{
nCounters++;
counter = theCounter;
limit=theLimit;
}
void Counter::increment()
{
if (counter<limit)
counter++;
}
void Counter::decrement()
{
if (counter>0)
counter--;
}
int Counter::getValue()
{
return counter;
}
int Counter::getNCounters()
{
return nCounters;
}
Write the implementation (.cpp file) of the Counter class of the previous exercise. The full specification of the class is:
A data member counter of type int .
An data member named limit of type int .
A static int data member named nCounters which is initialized to 0 .
A constructor that takes two int arguments and assigns the first one to counter and the second one to limit . It also adds one to the static variable nCounters
A function called increment that accepts no parameters and returns no value. If the data member counter is less than limit , increment just adds one to the instance variable counter .
A function called decrement that accepts no parameters and returns no value. If counter is greater than zero, decrement subtracts one from the counter .
A function called getValue that accepts no parameters. It returns the value of the instance variable counter .
A static function named getNCounters that accepts no parameters and return an int . getNCounters returns the value of the static variable nCounters .
Solution
int Counter::nCounters = 0;
Counter::Counter(int theCounter, int theLimit)
{
nCounters++;
counter = theCounter;
limit=theLimit;
}
void Counter::increment()
{
if (counter<limit)
counter++;
}
void Counter::decrement()
{
if (counter>0)
counter--;
}
int Counter::getValue()
{
return counter;
}
int Counter::getNCounters()
{
return nCounters;
}
Exericse Number
10877
13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10854
Question
Write the interface (.h file) of a class Counter containing:
An instance variable counter of type int , initialized to 0.
A function called increment that adds one to the instance variable counter . It does not accept parameters or return a value.
A function called getValue that doesn't accept any parameters. It returns the value of the instance variable counter .
A default constructor.
Solution
class Counter {
private:
int counter;
public:
void increment();
int getValue();
Counter();
};
Write the interface (.h file) of a class Counter containing:
An instance variable counter of type int , initialized to 0.
A function called increment that adds one to the instance variable counter . It does not accept parameters or return a value.
A function called getValue that doesn't accept any parameters. It returns the value of the instance variable counter .
A default constructor.
Solution
class Counter {
private:
int counter;
public:
void increment();
int getValue();
Counter();
};
Exericse Number
10854
13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10853
Question
Write the implementation (.cpp file) of the ContestResult class from the previous exercise. Again, the class contains:
An instance variable winner of type string , initialized to the empty string.
An instance variable secondPlace of type string , initialized to the empty string.
An instance variable thirdPlace of type String , initialized to the empty string.
A function called setWinner that has one parameter, whose value it assigns to the instance variable winner .
A function called setSecondPlace that has one parameter, whose value it assigns to the instance variable secondPlace .
A function called setThirdPlace that has one parameter, whose value it assigns to the instance variable thirdPlace .
A function called getWinner that has no parameters and that returns the value of the instance variable winner .
A function called getSecondPlace that has no parameters and that returns the value of the instance variable secondPlace .
A function called getThirdPlace that has no parameters and that returns the value of the instance variable thirdPlace .
Solution
void ContestResult::setWinner (string theWinner)
{
winner = theWinner;
}
void ContestResult::setSecondPlace (string theSecondPlace)
{
secondPlace = theSecondPlace;
}
void ContestResult::setThirdPlace (string theThirdPlace)
{
thirdPlace = theThirdPlace;
}
string ContestResult::getWinner ()
{
return winner;
}
string ContestResult::getSecondPlace()
{
return secondPlace;
}
string ContestResult::getThirdPlace()
{
return thirdPlace;
}
Write the implementation (.cpp file) of the ContestResult class from the previous exercise. Again, the class contains:
An instance variable winner of type string , initialized to the empty string.
An instance variable secondPlace of type string , initialized to the empty string.
An instance variable thirdPlace of type String , initialized to the empty string.
A function called setWinner that has one parameter, whose value it assigns to the instance variable winner .
A function called setSecondPlace that has one parameter, whose value it assigns to the instance variable secondPlace .
A function called setThirdPlace that has one parameter, whose value it assigns to the instance variable thirdPlace .
A function called getWinner that has no parameters and that returns the value of the instance variable winner .
A function called getSecondPlace that has no parameters and that returns the value of the instance variable secondPlace .
A function called getThirdPlace that has no parameters and that returns the value of the instance variable thirdPlace .
Solution
void ContestResult::setWinner (string theWinner)
{
winner = theWinner;
}
void ContestResult::setSecondPlace (string theSecondPlace)
{
secondPlace = theSecondPlace;
}
void ContestResult::setThirdPlace (string theThirdPlace)
{
thirdPlace = theThirdPlace;
}
string ContestResult::getWinner ()
{
return winner;
}
string ContestResult::getSecondPlace()
{
return secondPlace;
}
string ContestResult::getThirdPlace()
{
return thirdPlace;
}
Exericse Number
10583
13.3: Defining an Instance of a Class in C++: 11204
Question
Creating objects of the Currency class require a name (string), a currency symbol (string) and the number of decimal places (integer) usually associated with the currency (in that order). Creating objects of the Money class require a Currency object, and the actual amount (integer) (in that order). Define an object of type Currency named canadianDollars and corresponding to the name "Canadian Dollar", the symbol "C$", and 2 decimal places. Define an object of type Money named valueInCanadians corresponding to 230 units of canadianDollars.
Solution
Currency canadianDollars ("Canadian Dollar", "C$", 2);
Money valueInCanadians (canadianDollars,230);
Creating objects of the Currency class require a name (string), a currency symbol (string) and the number of decimal places (integer) usually associated with the currency (in that order). Creating objects of the Money class require a Currency object, and the actual amount (integer) (in that order). Define an object of type Currency named canadianDollars and corresponding to the name "Canadian Dollar", the symbol "C$", and 2 decimal places. Define an object of type Money named valueInCanadians corresponding to 230 units of canadianDollars.
Solution
Currency canadianDollars ("Canadian Dollar", "C$", 2);
Money valueInCanadians (canadianDollars,230);
Exericse Number
11204
13.3: Defining an Instance of a Class in C++: 11200
Question
Objects of the Window class require a width (integer) and a height (integer) be specified (in that order) upon definition. Declare two integers corresponding to a width and a length and read values into them from standard input (in that order). Use these value to define an object of type Window named newWindow.
Solution
int width, length;
cin >> width >> length;
Window newWindow (width, length);
Objects of the Window class require a width (integer) and a height (integer) be specified (in that order) upon definition. Declare two integers corresponding to a width and a length and read values into them from standard input (in that order). Use these value to define an object of type Window named newWindow.
Solution
int width, length;
cin >> width >> length;
Window newWindow (width, length);
Exericse Number
11200
13.3: Defining an Instance of a Class in C++: 11198
Question
Objects of the Window class require a width (integer) and a height (integer) be specified (in that order) upon definition. Define an object named window, of type Window, corresponding to a 80 x 20 window.
Solution
Window window (80,20);
Objects of the Window class require a width (integer) and a height (integer) be specified (in that order) upon definition. Define an object named window, of type Window, corresponding to a 80 x 20 window.
Solution
Window window (80,20);
Exericse Number
11198
13.3: Defining an Instance of a Class in C++: 11196
Question
Objects of the BankAccount class require a name (string) and a social security number (string) be specified (in that order)upon creation. Define an object named account , of type BankAccount , using the values "John Smith" and "123-45-6789" as the name and social security number respectively.
Solution
BankAccount account ("John Smith", "123-45-6789");
Objects of the BankAccount class require a name (string) and a social security number (string) be specified (in that order)upon creation. Define an object named account , of type BankAccount , using the values "John Smith" and "123-45-6789" as the name and social security number respectively.
Solution
BankAccount account ("John Smith", "123-45-6789");
Exericse Number
11196
CH12: Programming Challenge #15
Question
I only have a partial...anyone have more info send via comment.
SC-CUSTOM EXERCISE
I only have a partial...anyone have more info send via comment.
SC-CUSTOM EXERCISE
12.3: Passing File Stream Objects to Functions in C++ 11319
Question
Write the definition of a function named openLog . This function can be safely passed two arguments, an fstream object and a string object. The function associates the fstream with a file whose name is formed by concatenating the second argument with the suffix ".log". The fstream is made ready for output that is appended to the end of the file. If the file did not exist previously, false is returned; otherwise its content is deleted (truncated) and replaced by a single line:
PREVIOUS CONTENT DELETED
and true is returned.
Solution
If you have a solution, please send via comment
Write the definition of a function named openLog . This function can be safely passed two arguments, an fstream object and a string object. The function associates the fstream with a file whose name is formed by concatenating the second argument with the suffix ".log". The fstream is made ready for output that is appended to the end of the file. If the file did not exist previously, false is returned; otherwise its content is deleted (truncated) and replaced by a single line:
PREVIOUS CONTENT DELETED
and true is returned.
Solution
If you have a solution, please send via comment
12.2: File Output Formatting: 11308
Question
Given three variables, k, m, n, of type int that have already been declared and initialized, write some code that prints each of them left-justified in a 9-position field on the same line. For example, if their values were 27, 987654321, -4321, the output would be:
|27xxxxxxx987654321-4321xxxx
NOTE: The vertical bar, | , on the left above represents the left edge of the print area; it is not to be printed out. Also, we show x in the output above to represent spaces-- your output should not actually have x's!
Solution
cout.setf(ios::left, ios::adjustfield);
cout << setw(9) << k << setw(9) << m << setw(9) << n;
Given three variables, k, m, n, of type int that have already been declared and initialized, write some code that prints each of them left-justified in a 9-position field on the same line. For example, if their values were 27, 987654321, -4321, the output would be:
|27xxxxxxx987654321-4321xxxx
NOTE: The vertical bar, | , on the left above represents the left edge of the print area; it is not to be printed out. Also, we show x in the output above to represent spaces-- your output should not actually have x's!
Solution
cout.setf(ios::left, ios::adjustfield);
cout << setw(9) << k << setw(9) << m << setw(9) << n;
12.2: File Output Formatting: 11304
Question
Given three variables, a, b, c, of type double that have already been declared and initialized, write a statement that prints each of them on the same line, separated by one space, in such away that scientific (or e-notation or exponential notation) is avoided. Each number should be printed with 5 digits to the right of the decimal point. For example, if their values were 4.014268319, 14309, 0.00937608, the output would be:
|4.01427x14309.00000x0.00938
NOTE: The vertical bar, | , on the left above represents the left edge of the print area; it is not to be printed out. Also, we show x in the output above to represent spaces-- your output should not actually have x's!
Solution
cout << setprecision(5);
cout << fixed << a << " " << b << " " << c << " ";
Given three variables, a, b, c, of type double that have already been declared and initialized, write a statement that prints each of them on the same line, separated by one space, in such away that scientific (or e-notation or exponential notation) is avoided. Each number should be printed with 5 digits to the right of the decimal point. For example, if their values were 4.014268319, 14309, 0.00937608, the output would be:
|4.01427x14309.00000x0.00938
NOTE: The vertical bar, | , on the left above represents the left edge of the print area; it is not to be printed out. Also, we show x in the output above to represent spaces-- your output should not actually have x's!
Solution
cout << setprecision(5);
cout << fixed << a << " " << b << " " << c << " ";
12.1: File Operations: 11314
Question
Given an ifstream object named input , associate it with a file named hostdata by opening the file for input.
Solution
input.open("hostdata",ios::in);
Given an ifstream object named input , associate it with a file named hostdata by opening the file for input.
Solution
input.open("hostdata",ios::in);
12.1: File Operations: 11313
Question
Given an fstream object named menu , associate it with a file named todaysmenu.txt for output in a way that truncates (erases) any existing data in the file.
Solution
menu.open("todaysmenu.txt",ios::out);
Given an fstream object named menu , associate it with a file named todaysmenu.txt for output in a way that truncates (erases) any existing data in the file.
Solution
menu.open("todaysmenu.txt",ios::out);
Exericse Number
11313
12.1: File Operations: 11312
Question
Given an fstream object named todo , associate it with a file named todolist by opening the file for appending.
Solution
todo.open("todolist");
Given an fstream object named todo , associate it with a file named todolist by opening the file for appending.
Solution
todo.open("todolist");
Exericse Number
11312
12.1: File Operations: 11311
Question
Given an ofstream object named output , associate it with a file named yearsummary.txt for output in a way that truncates (erases) any existing data in the file.
Solution
output.open("yearsummary.txt",ios::trunc);
Given an ofstream object named output , associate it with a file named yearsummary.txt for output in a way that truncates (erases) any existing data in the file.
Solution
output.open("yearsummary.txt",ios::trunc);
Exericse Number
11311
11.6: Focus on Software Engineering: Nested Structures: 10752
11.6: Focus on Software Engineering: Nested Structures: 10752
Question
Assume that SREC has already been defined. Define a new type, ROSTER , that is a structure consisting of an int field, size , and another field, grades , that is an SREC array with 500 elements.
Solution
struct ROSTER
{
int size;
SREC grades[500];
};
Question
Assume that SREC has already been defined. Define a new type, ROSTER , that is a structure consisting of an int field, size , and another field, grades , that is an SREC array with 500 elements.
Solution
struct ROSTER
{
int size;
SREC grades[500];
};
Exericse Number
10752
11.3: Accessing Structure Members: 11153
Question
Assume you are given a variable, payRate of type Money (a structured type with two int fields, dollars and cents). Write the necessary code to increase the effective value of payRate by $1.50. To do this you need to add 50 to cents and 1 to dollars but you ALSO must make sure that cents does not end up over 99: if it does, you need to "carry a one" to dollars. For example, if payRate were $12.80 then a naive addition of $1.50 yields 13 (dollars) and 130 (cents). This would have to be changed to 14 (dollars) and 30 (cents).
Solution
Money payRateIncrease;
payRateIncrease.dollars=1;
payRateIncrease.cents=50;
payRate.dollars += payRateIncrease.dollars + (payRate.cents + payRateIncrease.cents)/100;
payRate.cents = (payRate.cents + payRateIncrease.cents) % 100;
Assume you are given a variable, payRate of type Money (a structured type with two int fields, dollars and cents). Write the necessary code to increase the effective value of payRate by $1.50. To do this you need to add 50 to cents and 1 to dollars but you ALSO must make sure that cents does not end up over 99: if it does, you need to "carry a one" to dollars. For example, if payRate were $12.80 then a naive addition of $1.50 yields 13 (dollars) and 130 (cents). This would have to be changed to 14 (dollars) and 30 (cents).
Solution
Money payRateIncrease;
payRateIncrease.dollars=1;
payRateIncrease.cents=50;
payRate.dollars += payRateIncrease.dollars + (payRate.cents + payRateIncrease.cents)/100;
payRate.cents = (payRate.cents + payRateIncrease.cents) % 100;
Exericse Number
11153
11.3: Accessing Structure Members: 11002
Question
The "origin" of the cartesian plane in math is the point where x and y are both zero. Given a variable, origin of type Point-- a structured type with two fields, x and y, both of type double, write one or two statements that make this variable's field's values consistent with the mathematical notion of "origin".
Solution
origin.x=0.0;
origin.y=0.0;
The "origin" of the cartesian plane in math is the point where x and y are both zero. Given a variable, origin of type Point-- a structured type with two fields, x and y, both of type double, write one or two statements that make this variable's field's values consistent with the mathematical notion of "origin".
Solution
origin.x=0.0;
origin.y=0.0;
11.2: Focus on Software Engineering: Combining Data into Structures: 11055
Question
Declare a structure whose tag name is Server and that contains the following fields: manufacturer, a string, model and serialnum, both also strings, year, an int, clockSpeed, a double, cores, an int, ram, an int and finally storage an int.
Solution
struct Server
{
string manufacturer, model, serialnum;
int year;
double clockSpeed;
int cores, ram, storage;
};
Declare a structure whose tag name is Server and that contains the following fields: manufacturer, a string, model and serialnum, both also strings, year, an int, clockSpeed, a double, cores, an int, ram, an int and finally storage an int.
Solution
struct Server
{
string manufacturer, model, serialnum;
int year;
double clockSpeed;
int cores, ram, storage;
};
11.2: Focus on Software Engineering: Combining Data into Structures: 10976
Question
Declare a structure whose tag name is Book and that contains exactly three fields (or members), each of type int. The first field is nCopies, the second field is nPages and the third field is nAuthors.
Solution
struct Book
{
int nCopies, nPages, nAuthors;
};
Declare a structure whose tag name is Book and that contains exactly three fields (or members), each of type int. The first field is nCopies, the second field is nPages and the third field is nAuthors.
Solution
struct Book
{
int nCopies, nPages, nAuthors;
};
11.2: Focus on Software Engineering: Combining Data into Structures: 11005
Question
Given the declaration of a structure whose tag is DATE write the declaration of the following variables enrolled_on, paid_on, and completed_on, each of which is of type DATE.
Solution
DATE enrolled_on, paid_on, completed_on;
Given the declaration of a structure whose tag is DATE write the declaration of the following variables enrolled_on, paid_on, and completed_on, each of which is of type DATE.
Solution
DATE enrolled_on, paid_on, completed_on;
CH10: Programming Challenge #18
Question
10.18: Phone Number List
Write a program that has an array of at least 50 string objects that hold people’s names and phone numbers. The program then reads lines of text from a file named phonebook into the array.
The program should ask the user to enter a name or partial name to search for in the array. All entries in the array that match the string entered should be displayed-- thus there may be more than one entry displayed.
Prompts And Output Labels. The program prints the message "Enter a name or partial name to search for: " and then after the user enters a some input and hits return, the program skips a line, and prints the heading: "Here are the results of the search:", followed by each matched string in the array on a line by itself.
Input Validation. None.
Solution (Raezorane R.)
#include
#include
#include
using namespace std;
int main()
{
const int SIZE = 50;
string phoneDirectory[SIZE];
int size=0;
string name; //name to look for
ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail()) {
getline(inFile,phoneDirectory[size]);
size++;
}
inFile.close();
// Get a name or partial name to search for.
cout << "Enter a name or partial name to search for: ";
getline(cin, name);
cout << "\nHere are the results of the search: " << endl;
int numberEntriesFound = 0;
for (int k = 0; k < size; k++)
{
if (phoneDirectory[k].find(name.data(), 0) < phoneDirectory[k].length())
{
numberEntriesFound ++;
cout << phoneDirectory[k] << endl;
}
}
if (numberEntriesFound == 0)
cout << "\nNo Entries were found for " << name;
return 0;
}
10.18: Phone Number List
Write a program that has an array of at least 50 string objects that hold people’s names and phone numbers. The program then reads lines of text from a file named phonebook into the array.
The program should ask the user to enter a name or partial name to search for in the array. All entries in the array that match the string entered should be displayed-- thus there may be more than one entry displayed.
Prompts And Output Labels. The program prints the message "Enter a name or partial name to search for: " and then after the user enters a some input and hits return, the program skips a line, and prints the heading: "Here are the results of the search:", followed by each matched string in the array on a line by itself.
Input Validation. None.
Solution (Raezorane R.)
#include
#include
#include
using namespace std;
int main()
{
const int SIZE = 50;
string phoneDirectory[SIZE];
int size=0;
string name; //name to look for
ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail()) {
getline(inFile,phoneDirectory[size]);
size++;
}
inFile.close();
// Get a name or partial name to search for.
cout << "Enter a name or partial name to search for: ";
getline(cin, name);
cout << "\nHere are the results of the search: " << endl;
int numberEntriesFound = 0;
for (int k = 0; k < size; k++)
{
if (phoneDirectory[k].find(name.data(), 0) < phoneDirectory[k].length())
{
numberEntriesFound ++;
cout << phoneDirectory[k] << endl;
}
}
if (numberEntriesFound == 0)
cout << "\nNo Entries were found for " << name;
return 0;
}
CH10: Programming Challenge #15
Question
10.15: Character Analysis
Write a program that reads the contents of a file named text.txt and determines the following:
The number of uppercase letters in the file
The number of lowercase letters in the file
The number of digits in the file
Prompts And Output Labels. There are no prompts-- nothing is read from standard in, just from the file text.txt. Each of the numbers calculated is displayed on a separate line on standard output, preceded by the following prompts (respectively): "Uppercase characters: ", "Lowercase characters: ", "Digits: ".
Input Validation. None.
Solution (By Raezorane R.)
// Chapter 10, Programming Challenge 15: Character Analysis
#include
#include
using namespace std;
int main()
{
char ch; // To hold a character from the file
// Counters for the number of uppercase characters,
// lowercase characters, and digits found in the file.
int uppercase = 0;
int lowercase = 0;
int digits = 0;
// Open the file.
ifstream inputFile;
inputFile.open("text.txt");
// Read each character in the file
// and analyze it.
while (inputFile >> ch)
{
if (isupper(ch))
uppercase++;
if (islower(ch))
lowercase++;
if (isdigit(ch))
digits++;
}
// Close the file.
inputFile.close();
// Display the results.
cout << "Uppercase characters: " << uppercase << endl;
cout << "Lowercase characters: " << lowercase << endl;
cout << "Digits: " << digits << endl;
return 0;
}
10.15: Character Analysis
Write a program that reads the contents of a file named text.txt and determines the following:
The number of uppercase letters in the file
The number of lowercase letters in the file
The number of digits in the file
Prompts And Output Labels. There are no prompts-- nothing is read from standard in, just from the file text.txt. Each of the numbers calculated is displayed on a separate line on standard output, preceded by the following prompts (respectively): "Uppercase characters: ", "Lowercase characters: ", "Digits: ".
Input Validation. None.
Solution (By Raezorane R.)
// Chapter 10, Programming Challenge 15: Character Analysis
#include
#include
using namespace std;
int main()
{
char ch; // To hold a character from the file
// Counters for the number of uppercase characters,
// lowercase characters, and digits found in the file.
int uppercase = 0;
int lowercase = 0;
int digits = 0;
// Open the file.
ifstream inputFile;
inputFile.open("text.txt");
// Read each character in the file
// and analyze it.
while (inputFile >> ch)
{
if (isupper(ch))
uppercase++;
if (islower(ch))
lowercase++;
if (isdigit(ch))
digits++;
}
// Close the file.
inputFile.close();
// Display the results.
cout << "Uppercase characters: " << uppercase << endl;
cout << "Lowercase characters: " << lowercase << endl;
cout << "Digits: " << digits << endl;
return 0;
}
10.7: More about the C++ string Class: 10864
Question
Assume that word is a variable of type string that has been assigned a value. Assume furthermore that this value always contains the letters "dr" followed by at least two other letters. For example: "undramatic", "dreck", "android", "no-drip".
Assume that there is another variable declared, drWord , also of type string . Write the statements needed so that the 4-character substring word of the value of word starting with "dr" is assigned to drWord . So, if the value of word were "George slew the dragon" your code would assign the value "drag" to drWord .
Solution
drWord = word.substr(word.find("dr"),4);
Assume that word is a variable of type string that has been assigned a value. Assume furthermore that this value always contains the letters "dr" followed by at least two other letters. For example: "undramatic", "dreck", "android", "no-drip".
Assume that there is another variable declared, drWord , also of type string . Write the statements needed so that the 4-character substring word of the value of word starting with "dr" is assigned to drWord . So, if the value of word were "George slew the dragon" your code would assign the value "drag" to drWord .
Solution
drWord = word.substr(word.find("dr"),4);
10.7: More about the C++ string Class: 10847
Question
Assume that name is a variable of type string that has been assigned a value. Write an expression whose value is the first character of the value of name . So if the value of name were "Smith" the expression's value would be 'S'.
Solution
name[0]
Assume that name is a variable of type string that has been assigned a value. Write an expression whose value is the first character of the value of name . So if the value of name were "Smith" the expression's value would be 'S'.
Solution
name[0]
10.4: Library Functions for Working with C-Strings: 10714
Question
Write a function max that has two C string parameters and returns the larger of the two.
Solution
char* max(char *a, char *b)
{
int result = strcmp(a, b);
if (result > 0)
return a;
else
return b;
}
Write a function max that has two C string parameters and returns the larger of the two.
Solution
char* max(char *a, char *b)
{
int result = strcmp(a, b);
if (result > 0)
return a;
else
return b;
}
Exericse Number
10714
10.4: Library Functions for Working with C-Strings: 10713
Question
Given the char * variables name1 , name2 , and name3 , write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values).
Solution
max=name1;
if (strcmp(name2, max)>0)
max=name2;
if (strcmp(name3,max)>0)
max=name3;
Given the char * variables name1 , name2 , and name3 , write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values).
Solution
max=name1;
if (strcmp(name2, max)>0)
max=name2;
if (strcmp(name3,max)>0)
max=name3;
10.3: C-Strings: 10900
Question
Assume that scotus is a two-dimensional character array that stores the family names (last names) of the nine justices on the Supreme Court of the United States. Assume no name is longer than twenty characters. Assume that scotus has been initialized in alphabetical order. Write an expression whose value is the last name stored in the array.
Solution
scotus[8]
Assume that scotus is a two-dimensional character array that stores the family names (last names) of the nine justices on the Supreme Court of the United States. Assume no name is longer than twenty characters. Assume that scotus has been initialized in alphabetical order. Write an expression whose value is the last name stored in the array.
Solution
scotus[8]
10.3: C-Strings: 11122
Question
Declare a char array named line suitable for storing C-strings as large as 50 characters, and write a statement that reads in the next line of standard input into this array. (Assume no line of input is 50 or more characters.)
Solution
char line[50];
cin.getline(line,50);
Declare a char array named line suitable for storing C-strings as large as 50 characters, and write a statement that reads in the next line of standard input into this array. (Assume no line of input is 50 or more characters.)
Solution
char line[50];
cin.getline(line,50);
Exericse Number
11122
Subscribe to:
Posts (Atom)