main-tutorial2

Adapted from Stephen J. Chenney’s Tutorial
Modified by Yu-Chi Lai in 2005
Modified by Yoh in 2007 (updated for VS05)

This tutorial will introduce you to use the command arguments.

Lets get started.

1.@ Step 1: What Are Command Line Arguments?

In the past DOS, we need to type in the command for executing the program instead of clicking the icon in the window system. We also need to parse in the parameters needed for the command to execute the program in the user’s desired way. In window, the GUI will be used to communicate with the user. In DOS, command line arguments are used to parse in users’ specified parameters. In the following figure, “C559 Tutorial 2.exe” is the command and So long and thanks for all the fish are the command line arguments being parsed in.

2.@ Step 2: Modify Main

  • Now that we have a window class we need to modify our main function to make use of it. Here’s the updated contents of main.cpp.
#include 
using namespace std;
int main(int argc, char** args)
{
	// Notice I start from i=1 not 0 because the args[0] is reserved 
    //        for the name of this program.
	for(int i = 1; i < argc; i++)
	{
	     cerr << i << "th argument is " << args[i] << "\n";
	}
}

This new version of main go through the command argument and then print all of them on the console.

3.@ Step 3: Modify Project’s Command Arguments Setting

  • Now we need to inform VS05 what our command line arguments are. Right click on our project (CS559 Tutorial 2), and choose Properties.

  • Choose Debugging from the left hand pane. Add I am your teaching assistant to the Command Arguments.
  • Click OK.

4.@ Step 4: Build Project

  • We are now ready to compile and link our program. Visual Studio calls this process building. Before building our project we need to open another window so we can see the results of our build attempt. Choose View -> Other Windows -> Output from the VS05 menus. The Ouput window shows the output from the compile and linking process. Feel free to dock or hide this window as we will need it rather infrequently.
  • Choose Build -> Build Solution from the VS05 menus. This should cause some text to be placed in the output window. If you’ve copied the code above correctly, you should see the following output to the right. If the build failed you should see some text explaining why it failed. If the error is a compiling error, you should be able to double click on the error and the source window should update to show you the line on which the error occured. For now we should have no errors so we’ve successfully built our project and we’re ready to run it.

5.@ Step 5: Run the Program

To run our program from within the VS05 enviroment we simply choose Debug -> Start Without Debugging. You should see this console window appear. Congratulations! You’ve got your first successfull VS05 project.

Source Code

Page last modified on September 03, 2007, at 04:32 PM