Name: ____________________________________________________ Alpha: _____________________

Describe help received: _________________________________________________________________

  1. [20pts] First run the following commands in the terminal:
    ~$ echo "1 2 3 4" > in.txt
    ~$ ls
    ~$ cat in.txt
    
    You will see a new file in.txt has been created, which contains four numbers (i.e., 1, 2, 3, and 4).
    You don't need to know this, but if you're curious: Roughly, the echo command works like cout in the terminal (i.e., output a string to the terminal), and the redirection operator > redirects (i.e., saves) the terminal output to a file.
    Now, consider the following code. The code creates a file out.txt, and then it simply tries to read all numbers from in.txt and write them to out.txt.
    
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    int main() {
      ifstream fin("in.txt");
      ofstream fout("out.txt");
    
      int n;
      while( fin ) {
        fin >> n;
        fout << n << " ";
      }
      fout << endl;
    
      return 0;
    }
    
    1. [5 pts] Copy and paste the above code into a new file called hw14_1.cpp. Then compile and run the program as follows:
      ~$ g++ hw14_1.cpp
      ~$ ./a.out
      ~$ cat out.txt
      
      Write the result of the last cat command (i.e., the contents of out.txt).
      
      
    2. [5 pts] Explain why the code does not work as we expected it to. If necessary, revisit the notes on File I/O (see the section "When file ends").
      
      
      
    3. [10 pts] Fix the above code by annotating it.

  2. [80pts] Write a program that reads in a file like this:
    3
    4
    23 788 12 -6 
    0 2 -337 -8923 
    25656 -89 0 1
    that contains a table of integers in unformatted text, and writes out a file output.html that shows the same table in html, which looks like this
    <table border=2>
    <tr><td>23</td><td>788</td><td>12</td><td>-6</td></tr>
    <tr><td>0</td><td>2</td><td>-337</td><td>-8923</td></tr>
    <tr><td>25656</td><td>-89</td><td>0</td><td>1</td></tr>
    </table>
      and renders like this  
    2378812-6
    02-337-8923
    25656-8901

    You must assume:

    Look at w3 tables intro if you need a little help with tables in HTML.

    Turn In a printout of your source code, and a printout of the table rendered by the browser when you open the file (use ctrl-o in your browser to open a file) output.html produced by your program with this input file. The result should look like:
    2378812-67
    02-337-89237
    25656-89017
    86714-20