Tuesday, November 17, 2015

C++ Simple Example of Using Arguments

C++ is a great language, largely because of its mid-level functionality. It can accomplish things at the system level as well as the user level. Here's  a simple example of working with arguments, including a help message if no arguments are passed...

#include <iostream>
int main(int argc, char* argv[])
  {
    if (argc < 2) {
      std::cerr << "Usage: " << argv[0] << " NAME" << std::endl;
      return 1;
      }
    std::cout << argv[0] << "says hello, " << argv[1] << "!" << std::endl;
    return 0;
  }

A few things to note about the code above:
  • The number of arguments and the argument string is passed directly 'main'.
  • Even though the user is to pass one argument, we check to make sure there are two arguments passed. This is because the program itself is considered the first argument.
  • We return a '1' when an argument is not passed by the user, but only after displaying help to the user. This is to record that the program did not end properly.
  • We return a '0' to show the program was executed properly.


No comments:

Post a Comment