Buscar este blog

jueves, 18 de febrero de 2016

C++ example with input arguments using flags

Hey!

I know it's been a long while since I last posted something in the blog. I just came across it some days ago and decided that I wanted to start writing again on it. So I will try to keep updating the blog from now on :)

Today's post is about a very simple, yet extremely common tool in programming: input arguments to programs. Whenever one launches a program from the terminal in Ubuntu (or command prompt in Windows), it is very normal to pass on arguments that are usually predefined by flags. In bash shell scripting language, one cannot actually think of programs that don't require input arguments. The example above is a really simple example of how this flags can be implemented to collect input arguments from the terminal (whenever the appropriate executable file has been created -using the g++ compiler, for example). This is a very simple implementation of a telephone list, where a new user is added via the flags as input arguments to the program, and the inputted user is then saved on to a file using the appropriate C++ classes (if- and ofstream).

So, as it used to be before, here are some examples of what the user may input:
  • Example 1: no input arguments. Since a user can only be added to the file through the command line, the program exits.


  •  Example 2: Adding a user in the command line using flags:


Now the user gets a message saying that "1 contact(s) ready to be saved. Select option 2". This option will write the saved user to a file, that is, it will append the new user to the end of the file contents. Once having done this, it will display a message like this:


Another option hat has been implemented is if the user just wants to see the address list. For that matter, if the --show flag is passed, it will read the file and show the contacts in the list:


This was just a really easy example on how to deal with input arguments with C++. Here is the code of the program, I hope you enjoy it!