15.15. Coding Practice

poem.txt
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.

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.

Example c192_cp_15_ac_1q
1#include <iostream>
2#include <fstream>
3
4// Write your code here.

Input File

Below are the contents of the input file.

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.

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.

Example c192_cp_15_ac_1a
 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." << std::endl;
12        std::exit(1);
13    }
14    for (std::size_t i = 0; i < 5; ++i) {
15        std::getline(infile, input);
16        std::cout << input << std::endl;
17    }
18}
speech.txt
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.

Practice selection

The legacy Runestone question pool c192_cp_15_ac_2_sq is represented by these exercises:

heights.txt
62   67      75      68      65
67   70      72      74      66
72   66      66      73      69
61   60      73      72      60

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.

Example c192_cp_15_ac_3q
1#include <iostream>
2#include <fstream>
3#include <vector>
4#include <algorithm>
5
6// Write your code here.

Input File

Below are the contents of the input file.

62    67      75      68      65
67    70      72      74      66
72    66      66      73      69
61    60      73      72      60

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.

Example c192_cp_15_ac_3a
 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." << std::endl;
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" << std::endl;
27}
powers.txt
Student output file

Practice selection

The legacy Runestone question pool c192_cp_15_ac_4_sq is represented by these exercises:

message.txt
Can you encrypt this message and decrypt the message below?
Pbatenghyngvbaf! Lbh'ir qrpelcgrq guvf zrffntr.

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.

Example c192_cp_15_ac_5q
1#include <iostream>
2#include <fstream>
3#include <cctype>
4
5int main() {
6    // Write your code here.
7}

Input File

Below are the contents of the input file.

Can you encrypt this message and decrypt the message below?
Pbatenghyngvbaf! Lbh'ir qrpelcgrq guvf zrffntr.

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.

Example c192_cp_15_ac_5a
 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." << std::endl;
37        std::exit(1);
38    }
39    while (std::getline(infile, message)) {
40        std::cout << ROT13(message) << std::endl;
41    }
42}
dream.txt
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?

Practice selection

The legacy Runestone question pool c192_cp_15_ac_6_sq is represented by these exercises:

class_data.txt
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

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.

Example c192_cp_15_ac_7q
1#include <iostream>
2#include <fstream>
3
4int main() {
5    // Write your code here.
6}

Input File

Below are the contents of the input file.

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

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.

Example c192_cp_15_ac_7a
 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." << std::endl;
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 << std::endl;
20        }
21    }
22}
shrimp.txt
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.

Practice selection

The legacy Runestone question pool c192_cp_15_ac_8_sq is represented by these exercises:

mult_table.txt
Student output file

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.

Example c192_cp_15_ac_9q
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.

Example c192_cp_15_ac_9a
 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." << std::endl;
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}

Practice selection

The legacy Runestone question pool c192_cp_15_ac_10_sq is represented by these exercises: