C++ Builder Tutorials

C++ Console Applications, part 2: Structure; Input and Output

In our previous lesson Setting up and compiling a C++ Console Application, you wrote this very basic example:

#pragma hdrstop
#pragma argsused
#include <iostream.h>
#include <conio.h>
#ifdef _WIN32
#include <tchar.h>
#else
  typedef char _TCHAR;
  #define _tmain main
#endif

#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
  char YourName[20];
  cout << "This is a console application.\n\n";
  cout << "Enter your name and press ENTER: ";
  cin << YourName;
  cout << "Hello, " << YourName << "!\n\n";
  cout << "Press ENTER to continue...\n";
  getchar();
  getchar();
  return 0;
}

Let's have a look at the source code in File1.cpp:

  • this unit is the program's main source unit.
  • #include statements say which other files are to be included into the application.
  • iostream.h is a header file. It is a C++ input/output library file, that contains mechanisms for displaying output on the screen and for taking input from the user.
  • conio.h is the header file that contains the declaration of getch().
  • int _tmain(int argc, _TCHAR* argv[]) is the main function of the program, executed as first when you run your C++ program.
    An empty template is written for you by C++ Builder. After the curly bracket { and before the line return 0; you add your code.

Handling Input and Output

In a console application, you don't use VCL controls for input and output. Communication with the user is handled with the cout << and cin << statements, and with getch():

  • char YourName[20] declares an array of 20 characters. It will hold what the user types in response to cin <<
  • The first cout << displays a line of text on the screen, followed by two end-of-line codes that each position the text cursor at the beginning of the next line.
  • cin << inputs keystrokes, until the ENTER ("return") key is pressed. Here, the resulting data are put in variable YourName.
  • The third cout << displays the text Hello, followed by the contents of array YourName, followed by a ! sign and two end-of-line codes.
  • getch() waits for the input of a single character. It pauses the program, giving the user time to read what is on the screen.
See also:

  Part 1: Setup