Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book 1.8. Exercise

1.8. Exercise

Copy the bigdigits directory to, say, my_bigdigits, and modify my_bigdigits/bigdigits.go to produce a version of the bigdigits program (§1.4, 16 →) that can optionally output the number with an overbar and underbar of “ *”s, and with improved command-line argument handling.

The original program output its usage message if no number was given; change this so that the usage message is also output if the user gives an argument of -h or --help. For example:


If the --bar (or -b) option is not present the program should have the same behavior as before. Here is an example of the expected output if the option is present:


The solution requires more elaborate command-line processing than the version shown in the text, although the code producing the output only needs a small change to output the overbar before the first row and the underbar after the last row. Overall, the solution needs about 20 extra lines of code—the solution’s main() function is twice as long as the original (~40 vs. ~20 lines), mostly due to the code needed to handle the command line. A solution is provided in the file bigdigits_ans/bigdigits.go.

Hints: The solution also has a subtle difference in the way it builds up each row’s line to prevent the bars extending too far. Also, the solution imports the strings package and uses the strings.Repeat(string, int) function. This function returns a string that contains the stringit is given as its first argument repeated by the number of times of the int given as its second argument. Why not look this function up either locally (see the sidebar “The Go Documentation”; 8 ←), or at golang.org/pkg/strings, and start to become familiar with the Go standard library’s documentation.

It would be much easier to handle command-line arguments using a package designed for the purpose. Go’s standard library includes a rather basic command line parsing package, flag, that supports X11-style options (e.g., -option). In addition, several option parsers that support GNU-style short and long options (e.g., -o and --option) are available from godashboard.appspot.com/project.

  • + Share This
  • 🔖 Save To Your Account