15.15. Coding Practice¶
Question
Write a program that takes in an input file called heights.txt,
finds the median of the data, and prints
"The median height is: height inches" to the terminal.
Include proper file error checking.
1#include <iostream>
2#include <fstream>
3#include <vector>
4#include <algorithm>
5
6// Write your code here.
Answer
Below is one way to implement this program. We create an ifstream object
to open our file. We check to make sure the file is opened correctly before
we read the data values into a vector. After sorting the vector, we find
the median depending on whether the number of data values was even or odd.
Finally, we output our result to the terminal.
1#include <cstdlib>
2#include <iostream>
3#include <fstream>
4#include <vector>
5#include <algorithm>
6
7int main() {
8 std::ifstream infile("heights.txt");
9 std::vector<int> data;
10 double median;
11 int height;
12 if (!infile.good()) {
13 std::cout << "Error. Unable to open file." << '\n';
14 std::exit(1);
15 }
16 while (infile >> height) {
17 data.push_back(height);
18 }
19 sort(data.begin(), data.end());
20 if (data.size() % 2 == 0) {
21 median = (data[data.size() / 2 - 1] + data[data.size() / 2]) / 2.0;
22 }
23 else {
24 median = data[data.size() / 2];
25 }
26 std::cout << "The median height is: " << median << " inches" << '\n';
27}
Question
ROT13 is a simple Caesar cipher that replaces each letter in a string
with the 13th letter after it in the alphabet. For example, using ROT13
on the letter "a" would turn it into "n". Notice how since 13 is exactly
half the number of characters in the alphabet, using ROT13 on the letter
"n" would turn it into "a". Thus, ROT13 can be used to encrypt and decrypt
messages. Write a program that takes in an input file called message.txt,
applies ROT13, and outputs the result to the terminal.
Include proper file error checking.
1#include <iostream>
2#include <fstream>
3#include <cctype>
4
5int main() {
6 // Write your code here.
7}
Answer
Below is one way to implement this program. We create an ifstream object
to open our file. We check to make sure the file is opened correctly before
we read the data values into a string. We call our ROT13 function and
output the result to the output file.
1#include <cstddef>
2#include <cstdlib>
3#include <string>
4#include <iostream>
5#include <fstream>
6#include <cctype>
7
8std::string ROT13 (std::string message) {
9 for (std::size_t i = 0; i < message.size(); ++i) {
10 if (std::isalpha(static_cast<unsigned char>(message[i]))) {
11 if (message[i] >= 'A' && message[i] <= 'Z') {
12 if (message[i] <= 'M') {
13 message[i] = message[i] + 13;
14 }
15 else {
16 message[i] = message[i] - 13;
17 }
18 }
19 else {
20 if (message[i] <= 'm') {
21 message[i] = message[i] + 13;
22 }
23 else {
24 message[i] = message[i] - 13;
25 }
26 }
27 }
28 }
29 return message;
30}
31
32int main() {
33 std::ifstream infile("message.txt");
34 std::string message;
35 if (!infile.good()) {
36 std::cout << "Error. Unable to open file." << '\n';
37 std::exit(1);
38 }
39 while (std::getline(infile, message)) {
40 std::cout << ROT13(message) << '\n';
41 }
42}
Question
Write a program that reads in data about a class from the file
class_data.txt and outputs the rows of data where a
student has a GPA of at least 3.5. Include proper file error checking.
1#include <iostream>
2#include <fstream>
3
4int main() {
5 // Write your code here.
6}
Answer
Below is one way to implement this program. We create an ifstream object
to open our file. We check to make sure the file is opened correctly before
we read the data values into corresponding variables. We check if the GPA
is at least 3.5, and print the data values to the terminal if so.
1#include <cstdlib>
2#include <string>
3#include <iostream>
4#include <fstream>
5
6int main() {
7 std::ifstream infile("class_data.txt");
8 std::string fname, lname;
9 int grade, age;
10 double gpa;
11 if (!infile.good()) {
12 std::cout << "Error. Unable to open file." << '\n';
13 std::exit(1);
14 }
15 std::getline(infile, fname);
16 while (infile >> fname >> lname >> grade >> gpa >> age) {
17 if (gpa >= 3.5) {
18 std::cout << fname << '\t' << lname << '\t' << grade
19 << '\t' << gpa << '\t' << age << '\n';
20 }
21 }
22}
Question
Write a program that creates a multiplication table for the first 10
numbers using a matrix and outputting the table to an output file
called mult_table.txt. Include proper file error checking.
1#include <iostream>
2#include <fstream>
3#include <vector>
4
5int main() {
6 // Write your code here.
7}
Answer
Below is one way to implement this program. We create a 10x10 matrix and fill in the products. Then we traverse through the matrix and output the values into the output file.
1#include <cstddef>
2#include <cstdlib>
3#include <iostream>
4#include <fstream>
5#include <vector>
6
7int main() {
8 std::ofstream outfile("mult_table.txt");
9 if (!outfile.good()) {
10 std::cout << "Error. Unable to open file." << '\n';
11 std::exit(1);
12 }
13 std::vector<std::size_t> rows(10);
14 std::vector<std::vector<std::size_t>> mat;
15 for (std::size_t i = 0; i < 10; ++i) {
16 mat.push_back(rows);
17 }
18 for (std::size_t i = 0; i < 10; ++i) {
19 for (std::size_t j = 0; j < 10; ++j) {
20 mat[i][j] = (i + 1) * (j + 1);
21 }
22 }
23 for (std::size_t i = 0; i < 10; ++i) {
24 for (std::size_t j = 0; j < 10; ++j) {
25 outfile << mat[i][j] << '\t';
26 }
27 outfile << '\n';
28 }
29}
Question
Write a program that takes in an input file called poem.txt
and prints the first 5 lines to the terminal. Include proper
file error checking.
1#include <iostream>
2#include <fstream>
3
4// Write your code here.
Answer
Below is one way to implement this program. We create an ifstream object
to open our file. We check to make sure the file is opened correctly before
we use getline in a for loop to retrieve and print the first 5
lines of the poem.
1#include <cstddef>
2#include <cstdlib>
3#include <string>
4#include <iostream>
5#include <fstream>
6
7int main() {
8 std::ifstream infile("poem.txt");
9 std::string input;
10 if (!infile.good()) {
11 std::cout << "Error. Unable to open file." << '\n';
12 std::exit(1);
13 }
14 for (std::size_t i = 0; i < 5; ++i) {
15 std::getline(infile, input);
16 std::cout << input << '\n';
17 }
18}
Question
Write a program that prompts a user for the name of an input file
and for an integer n. Then open the file and output the first
n lines of the file with each line reversed. For example,
if you read in the line "hello world" you should print out
"dlrow olleh" to the terminal. Include proper file error checking.
Use the code prompt to write your solution.
1#include <iostream>
2#include <fstream>
3
4// Write your code here.
Question
Write a program that prompts a user for an integer n and print the first n
powers of 2 to an output file called powers.txt. Include proper file error checking.
To simulate what your output file would look like, the contents of your output file
will be displayed on the terminal. Use the code prompt to write your solution.
1#include <string>
2#include <iostream>
3#include <fstream>
4#include <cmath>
5
6int main() {
7 // Write your code here.
8
9
10
11
12
13 // Do not modify the code below
14 std::ifstream student_output("powers.txt");
15 if (!student_output.good()) {
16 std::cout << "Error opening student's output." << '\n';
17 }
18 std::string answer;
19 while (std::getline(student_output, answer)) {
20 std::cout << answer << '\n';
21 }
22}
Question
Write a program that takes an input file called "dream.txt" and outputs the number of times the string "you" appears in the file to the terminal. Include proper file error checking. Use the code prompt to write your solution.
1#include <iostream>
2#include <fstream>
3
4// Write your code here.
Question
Write a program that takes an input file called "shrimp.txt" and outputs the quote with "shrimp" replaced by a word that the user inputs to the terminal. Include proper file error checking. Use the code prompt to write your solution.
1#include <iostream>
2#include <fstream>
3
4// Write your code here.
Question
Multiply a two-by-three array by a three-by-two array. The result has two rows and two columns. For each result element, sum the products of the corresponding row and column entries.
1#include <array>
2#include <cstddef>
3#include <iostream>
4
5int main() {
6 std::array<std::array<int, 3>, 2> a{{{1, 2, 3}, {4, 5, 6}}};
7 std::array<std::array<int, 2>, 3> b{{{7, 8}, {9, 10}, {11, 12}}};
8 // Write your multiplication and print the result.
9}
Question
We have a file called "locations.txt" that we want to read data from. Check to make sure that the file was opened properly; if it wasn't, display an error message and exit with a status of 1.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to write code that makes sure the file was opened properly.
1#include <cstdlib>
2#include <fstream>
3#include <iostream>
4
5int main() {
6 std::ifstream infile("locations.txt");
7 if (infile.good() == false) {
8 std::cout << "Unable to open the file." << '\n';
9 std::exit(1);
10 }
11}
Question
Let's write a program that prompts the user for a filename and opens that file.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to write the program.
1#include <cstdlib>
2#include <fstream>
3#include <string>
4#include <iostream>
5
6int main() {
7 std::string filename;
8 std::cout << "Enter the name of the file: ";
9 std::cin >> filename;
10 std::ifstream infile(filename);
11 if (infile.good() == false) {
12 std::cout << "Unable to open the file." << '\n';
13 std::exit(1);
14 }
15}
Question
Now let's write some output to a file. Write a program that prompts a user for a list of 5 integers separated by spaces, calculates the average of those integers, and outputs "The average is
average" to an output file called "average.txt". Put the necessary blocks of code in the correct order. Declare the output file first and check that it is opened correctly.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to write the program.
1#include <cstdlib>
2#include <fstream>
3#include <iostream>
4
5int main() {
6 std::ofstream outfile("average.txt");
7 if (outfile.good() == false) {
8 std::cout << "Unable to open the file." << '\n';
9 std::exit(1);
10 }
11 int sum = 0;
12 int n1, n2, n3, n4, n5;
13 std::cout << "Enter five integers separated by spaces: ";
14 if (!(std::cin >> n1 >> n2 >> n3 >> n4 >> n5)) return 1;
15 sum = n1 + n2 + n3 + n4 + n5;
16 outfile << "The average is " << sum / 5.0 << '\n';
17}
Question
We are given a file called "data.txt" with an unknown number of
doublevalues. Write a program that finds the minimum, maximum, and number of data and outputs these values to a file called "summary.txt". Declare the input and output files first, and check to see that both are opened correctly before dealing with data. Increment the number of data points before checking for the min and max.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to write the code.
1#include <cstddef>
2#include <cstdlib>
3#include <fstream>
4#include <iostream>
5
6int main() {
7 std::ifstream infile("data.txt");
8 std::ofstream outfile("summary.txt");
9 if (infile.good() == false || outfile.good() == false) {
10 std::cout << "Unable to open a file." << '\n';
11 std::exit(1);
12 }
13 std::size_t num_data = 1;
14 double min, max, value;
15 if (!(infile >> value)) { return 1; }
16 min = value;
17 max = value;
18 while (infile >> value) {
19 ++num_data;
20 if (value < min) { min = value; }
21 if (value > max) { max = value; }
22 }
23 outfile << "Number of data: " << num_data << ", min: " << min << ", max: " << max << '\n';
24}
Question
You are given a file called "employee_data.txt" and you want to store the information from that file into a vector of data. The file contains information about an employee's first and last name, age, phone number, and email. Write the definition of an
employeebefore you write yourmainfunction. Open and check the file before working with the data.
1#include <iostream>
2#include <string>
3#include <vector>
4// YOUR CODE HERE
Answer
Below is one way to define
employee.
1#include <cstdlib>
2#include <fstream>
3#include <iostream>
4#include <string>
5#include <vector>
6
7struct employee {
8 std::string fname;
9 std::string lname;
10 int age;
11 int phone;
12 std::string email;
13 employee(std::string f, std::string l, int a, int p, std::string e) {
14 fname = f;
15 lname = l;
16 age = a;
17 phone = p;
18 email = e;
19 }
20};
21
22int main() {
23 std::ifstream infile("employee_data.txt");
24 if (infile.good() == false) {
25 std::cout << "Unable to open the file." << '\n';
26 std::exit(1);
27 }
28 std::vector<employee> data;
29 std::string fname, lname, email;
30 int age, phone;
31 while (infile >> fname >> lname >> age >> phone >> email) {
32 employee e(fname, lname, age, phone, email);
33 data.push_back(e);
34 }
35}
Question
You are given a file but it appears that someone's capslock key was stuck because everything is in uppercase. Write a program that takes the input from the file "UPPER.txt" and converts all the words to lowercase and prints out the modified message to a file called "lower.txt". Write the definition of the function
to_lowerfirst. Separate the words with spaces.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to write the program and
to_lowerfunction.
1#include <cctype>
2#include <cstddef>
3#include <cstdlib>
4#include <fstream>
5#include <iostream>
6#include <string>
7
8std::string upper_to_lower(std::string upper) {
9 for (std::size_t i = 0; i < upper.length(); ++i) {
10 upper[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(upper[i])));
11 }
12 return upper;
13}
14
15int main() {
16 std::ifstream infile("UPPER.txt");
17 std::ofstream outfile("lower.txt");
18 if (infile.good() == false || outfile.good() == false) {
19 std::cout << "Unable to open a file." << '\n';
20 std::exit(1);
21 }
22 std::string word;
23 while (infile >> word) {
24 std::string upper = upper_to_lower(word);
25 outfile << upper << ' ';
26 }
27}
Question
Nobody ever put a limit on how many files we can work with. Does this mean we can open two or more files at once? Yes we can! Write a program that combines two files "odds.txt" and "evens.txt" into one output file "numbers.txt". You should combine them in a way such that "numbers.txt" contains the first odd number then the first even number then the second odd number and so on. You are guaranteed that there are equal amounts of odd and even numbers.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to write the prgram.
1#include <cstdlib>
2#include <fstream>
3#include <iostream>
4
5int main() {
6 std::ifstream odds("odds.txt");
7 std::ifstream evens("evens.txt");
8 std::ofstream outfile("numbers.txt");
9 if (!odds.good() || !evens.good() || !outfile.good()) {
10 std::cout << "Unable to open a file." << '\n';
11 std::exit(1);
12 }
13 int odd, even;
14 while (odds >> odd && evens >> even) {
15 outfile << odd << ' ' << even << ' ';
16 }
17}
Question
Convert a vector of names to a set of unique names.
1#include <cstddef>
2#include <iostream>
3#include <map>
4#include <set>
5#include <string>
6#include <vector>
7
8// Write your function and a main that demonstrates it.
Answer
1#include <cstddef>
2#include <iostream>
3#include <map>
4#include <set>
5#include <string>
6#include <vector>
7
8std::set<std::string> vector_to_set(const std::vector<std::string>& data) {
9 std::set<std::string> names;
10 for (const auto& name : data) {
11 names.insert(name);
12 }
13 return names;
14}
15
16int main() {
17 auto names = vector_to_set({"Boston", "Chicago", "Boston"});
18 for (const auto& name : names) { std::cout << name << '\n'; }
19}
Question
Create a rectangular table with rows and columns supplied at run time. Initialize all entries to zero.
1#include <cstddef>
2#include <iostream>
3#include <map>
4#include <set>
5#include <string>
6#include <vector>
7
8// Write your function and a main that demonstrates it.
Answer
1#include <cstddef>
2#include <iostream>
3#include <map>
4#include <set>
5#include <string>
6#include <vector>
7
8std::vector<std::vector<int>> make_table(std::size_t rows, std::size_t columns) {
9 return std::vector<std::vector<int>>(rows, std::vector<int>(columns, 0));
10}
11
12int main() {
13 auto table = make_table(2, 3);
14 table.at(1).at(2) = 7;
15 std::cout << table.at(1).at(2) << '\n';
16}
Question
Count repeated city names with a map. Return the frequency of each name.
1#include <cstddef>
2#include <iostream>
3#include <map>
4#include <set>
5#include <string>
6#include <vector>
7
8// Write your function and a main that demonstrates it.
Answer
1#include <cstddef>
2#include <iostream>
3#include <map>
4#include <set>
5#include <string>
6#include <vector>
7
8std::map<std::string, std::size_t> count_cities(const std::vector<std::string>& names) {
9 std::map<std::string, std::size_t> counts;
10 for (const auto& name : names) {
11 ++counts[name];
12 }
13 return counts;
14}
15
16int main() {
17 auto counts = count_cities({"Boston", "Chicago", "Boston"});
18 for (const auto& [name, count] : counts) {
19 std::cout << name << ": " << count << '\n';
20 }
21}
15.16. Files used in the practice¶
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear,
Though as for that the passing there
Had worn them really about the same,
And both that morning equally lay
In leaves no step had trodden black.
Oh, I kept the first for another day!
Yet knowing how way leads on to way
I doubted if I should ever come back.
I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference.
62 67 75 68 65
67 70 72 74 66
72 66 66 73 69
61 60 73 72 60
student output file
Have you ever had a dream that you,
um, you had, your, you- you could,
you’ll do, you- you wants, you, you
could do so, you- you’ll do, you could-
you, you want, you want them to do you
so much you could do anything?
There's pineapple shrimp, lemon shrimp, coconut shrimp,
pepper shrimp, shrimp soup, shrimp stew, shrimp salad,
shrimp and potatoes, shrimp burger, shrimp sandwich.
That- that's about it.
Can you encrypt this message and decrypt the message below?
Pbatenghyngvbaf! Lbh'ir qrpelcgrq guvf zrffntr.
First Last Grade GPA Age
Alex Jones 9 3.4 14
Beth Hamilton 12 3.7 18
Charles White 11 3.5 16
Daniel Kim 10 3.8 16
Ethan Brooks 11 3.9 17
Faith Flemmings 10 3.0 15
Gina Zhou 9 3.2 14
student output file
We choose to go to the Moon. We choose to go to the Moon...
We choose to go to the Moon in this decade and do the other things,
not because they are easy, but because they are hard; because that goal
will serve to organize and measure the best of our energies and skills,
because that challenge is one that we are willing to accept, one we are
unwilling to postpone, and one we intend to win, and the others, too.