C++ Quick Guide

C++ Quick Guide ”; Previous Next C++ Overview C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming. C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features. C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983. C++ is a superset of C, and that virtually any legal C program is a legal C++ program. Note − A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time. Object-Oriented Programming C++ fully supports object-oriented programming, including the four pillars of object-oriented development − Encapsulation Data hiding Inheritance Polymorphism Standard Libraries Standard C++ consists of three important parts − The core language giving all the building blocks including variables, data types and literals, etc. The C++ Standard Library giving a rich set of functions manipulating files, strings, etc. The Standard Template Library (STL) giving a rich set of methods manipulating data structures, etc. The ANSI Standard The ANSI standard is an attempt to ensure that C++ is portable; that code you write for Microsoft”s compiler will compile without errors, using a compiler on a Mac, UNIX, a Windows box, or an Alpha. The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers support the ANSI standard. Learning C++ The most important thing while learning C++ is to focus on concepts. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. C++ supports a variety of programming styles. You can write in the style of Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining runtime and space efficiency. Use of C++ C++ is used by hundreds of thousands of programmers in essentially every application domain. C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware under realtime constraints. C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts. Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++. C++ Environment Setup Local Environment Setup If you are still willing to set up your environment for C++, you need to have the following two softwares on your computer. Text Editor This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or UNIX. The files you create with your editor are called source files and for C++ they typically are named with the extension .cpp, .cp, or .c. A text editor should be in place to start your C++ programming. C++ Compiler This is an actual C++ compiler, which will be used to compile your source code into final executable program. Most C++ compilers don”t care what extension you give to your source code, but if you don”t specify otherwise, many will use .cpp by default. Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective Operating Systems. Installing GNU C/C++ Compiler UNIX/Linux Installation If you are using Linux or UNIX then check whether GCC is installed on your system by entering the following command from the command line − $ g++ -v If you have installed GCC, then it should print a message such as the following − Using built-in specs. Target: i386-redhat-linux Configured with: ../configure –prefix=/usr ……. Thread model: posix gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/ Mac OS X Installation If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple”s website and follow the simple installation instructions. Xcode is currently available at developer.apple.com/technologies/tools/. Windows Installation To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program which should be named MinGW-<version>.exe. While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more. Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names. When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line. C++ Basic Syntax When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other”s methods. Let us now briefly look into what a class, object, methods, and instant variables mean. Object − Objects have states and behaviors. Example: A dog has states – color, name, breed as well as behaviors – wagging, barking, eating. An object is an instance of a class. Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support. Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are

C++ Constants/Literals

C++ Constants/Literals ”; Previous Next Constants refer to fixed values that the program may not alter and they are called literals. Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values. Again, constants are treated just like regular variables except that their values cannot be modified after their definition. Integer Literals An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals − 212 // Legal 215u // Legal 0xFeeL // Legal 078 // Illegal: 8 is not an octal digit 032UU // Illegal: cannot repeat a suffix Following are other examples of various types of Integer literals − 85 // decimal 0213 // octal 0x4b // hexadecimal 30 // int 30u // unsigned int 30l // long 30ul // unsigned long Floating-point Literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals − 3.14159 // Legal 314159E-5L // Legal 510E // Illegal: incomplete exponent 210f // Illegal: no decimal or exponent .e55 // Illegal: missing integer or fraction Boolean Literals There are two Boolean literals and they are part of standard C++ keywords − A value of true representing true. A value of false representing false. You should not consider the value of true equal to 1 and value of false equal to 0. Character Literals Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide character literal (e.g., L”x”) and should be stored in wchar_t type of variable . Otherwise, it is a narrow character literal (e.g., ”x”) and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., ”x”), an escape sequence (e.g., ”t”), or a universal character (e.g., ”u02C0”). There are certain characters in C++ when they are preceded by a backslash they will have special meaning and they are used to represent like newline (n) or tab (t). Here, you have a list of some of such escape sequence codes − Escape sequence Meaning \ character ” ” character “ ” character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab ooo Octal number of one to three digits xhh . . . Hexadecimal number of one or more digits Following is the example to show a few escape sequence characters − Live Demo #include <iostream> using namespace std; int main() { cout << “HellotWorldnn”; return 0; } When the above code is compiled and executed, it produces the following result − Hello World String Literals String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separate them using whitespaces. Here are some examples of string literals. All the three forms are identical strings. “hello, dear” “hello, dear” “hello, ” “d” “ear” Defining Constants There are two simple ways in C++ to define constants − Using #define preprocessor. Using const keyword. The #define Preprocessor Following is the form to use #define preprocessor to define a constant − #define identifier value Following example explains it in detail − Live Demo #include <iostream> using namespace std; #define LENGTH 10 #define WIDTH 5 #define NEWLINE ”n” int main() { int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; } When the above code is compiled and executed, it produces the following result − 50 The const Keyword You can use const prefix to declare constants with a specific type as follows − const type variable = value; Following example explains it in detail − Live Demo #include <iostream> using namespace std; int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = ”n”; int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; } When the above code is compiled and executed, it produces the following result − 50 Note that it is a good programming practice to define constants in CAPITALS. Print Page Previous Next Advertisements ”;

C++ Multiple Variables

C++ Declare Multiple Variables ”; Previous Next C++ programming language allows programmers to declare multiple variables in a single statement without any line breaks. This is only possible for variables which belong to the same data type. How to Declare Multiple Variables in C++? This is executed using a comma (,) separated list of variables with different variables names, and the data types must be the same for all variables to be declared. Multiple variables declaration is supported for all data types in C++, for example, we can declare multiple strings with different names in a single statement using a comma separated list. Syntax The following syntax shows how to declare multiple variables with same data types in a single statement − data_type var_a, var_b, var_; Example The following exemplar code shows how to declare multiple variables with same data types in a single statement − #include <iostream> using namespace std; int main() { int y,z,x; x=10; y=20; z=30; cout<<“value of x: “<<x<<endl<<“value of y: “<<y<<endl<<“value of z: “<<z; return 0; } Output value of x: 10 value of y: 20 value of z: 30 Initialize Multiple Variables The variables can also be initialized with different values in the same statement of declaration, which makes it easy to declare variables of different values. Syntax The following syntax shows how to declare multiple variables, and initialize them with values in a single statement − data_type var_a=[value1], var_b, var_c=[value3]; Here, var_a, var_b and var_c are variables of same data type, and [value] is the value of that variable. Example The following exemplar code shows how to declare multiple variables, and initialize them with values in a single statement − #include <iostream> using namespace std; int main() { int y=10,z=20,x; x=10; cout<<“value of x: “<<x<<endl<<“value of y: “<<y<<endl<<“value of z: “<<z; return 0; } Output value of x: 10 value of y: 10 value of z: 20 Initialize Multiple Variables with Same Value The variables can also be initialized with the same values in a single statement using the “=” operator multiple times in a single statement. Syntax The following syntax shows how to declare multiple variables and initialize all of them to a single value in a single statement − data_type var_1, var_2, var_3; var_1=var_2=var_3= [value] Here, the variables var_1, var_2 and var_3 are initialized to a single value [value] in a single statement. Example The following exemplar code shows how to declare multiple variables and initialize all of them to a single value in a single statement − #include <iostream> using namespace std; int main() { int y,z; int x=y=z=10; cout<<“value of x: “<<x<<endl<<“value of y: “<<y<<endl<<“value of z: “<<z; return 0; } Output value of x: 10 value of y: 10 value of z: 10 Print Page Previous Next Advertisements ”;

C++ Loop Types

C++ Loop Types ”; Previous Next There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages − C++ programming language provides the following type of loops to handle looping requirements. Sr.No Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 do…while loop Like a ‘while’ statement, except that it tests the condition at the end of the loop body. 4 nested loops You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C++ supports the following control statements. Sr.No Control Statement & Description 1 break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 3 goto statement Transfers control to the labeled statement. Though it is not advised to use goto statement in your program. The Infinite Loop A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty. #include <iostream> using namespace std; int main () { for( ; ; ) { printf(“This loop will run forever.n”); } return 0; } When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop. NOTE − You can terminate an infinite loop by pressing Ctrl + C keys. Print Page Previous Next Advertisements ”;

C++ Discussion

Discuss C++ ”; Previous Next C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial adopts a simple and practical approach to describe the concepts of C++. Print Page Previous Next Advertisements ”;

C++ Decision Making

C++ decision making statements ”; Previous Next Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − C++ programming language provides following types of decision making statements. Sr.No Statement & Description 1 if statement An ‘if’ statement consists of a boolean expression followed by one or more statements. 2 if…else statement An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the boolean expression is false. 3 switch statement A ‘switch’ statement allows a variable to be tested for equality against a list of values. 4 nested if statements You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s). 5 nested switch statements You can use one ‘switch’ statement inside another ‘switch’ statement(s). The ? : Operator We have covered conditional operator “? :” in previous chapter which can be used to replace if…else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Print Page Previous Next Advertisements ”;

C++ Numeric Data Types

C++ Numeric Data Types ”; Previous Next Numeric data types in C++ are used to handle numerical data like integers (both signed and unsigned), floating-point values, and precision values. Numeric data types mainly contain three fundamental types of numeric data, which are as follows − Int Int Short Int Long Int Long Long Int Unsigned Int Unsigned Short Int Unsigned Long Int Unsigned Long Long Int Float Double Long Double In this article, we will go through all of the numeric data types and their subtypes in detail with examples. int Data Type The int data type is short for integer, which takes numeric values from -231 to (231-1). It takes 4 Bytes (i.e., 32 bits) in the memory. Syntax int variable_name; It is further classified into various derived subtypes, which are as follows − (a) short int The short int is used for smaller numbers, as it takes only 2 Bytes (i.e., 16 bits) in the memory. It”s value ranges from -215to (215-1). Syntax short int varianle_name; (b) long int The long int is used for bigger numbers, with memory space of 4 bytes (i.e., 32 bits), and can be up to 8 bytes (i.e., 64 bits), depending upon the compiler. Syntax long int variable_name; (c) long long int The long long int is used for larger numbers, with memory space of 8 bytes (i.e. 64 bits), and can be up to 16 bytes (i.e., 128 bits), depending upon the compiler. It”s value ranges from -263 to (263-1). Syntax long long int variable_name; (d) unsigned int The unsigned int is used to store only non-negative value, and take up same memory space as an int data type, which is 4 Bytes (i.e. 32 bits). It”s value ranges from 0 to (232-1). Syntax unsigned int variable_name; (e) unsigned short int The unsigned short int is used to store only non-negative value, and take up same memory space as a short int data type, which is 2 Bytes (i.e., 16 bits). It”s value ranges from 0 to (216-1). Syntax unsigned short int variable_name; (f) unsigned long int The unsigned long int is used to store only non-negative value, and take up same memory space as a long int data type, which ranges from 4 Bytes (i.e., 32 bits) to 8 Bytes (i.e., 64 bits). Syntax unsigned long int variable_name; (g) unsigned long long int The unsigned long long int is used to store only non-negative value, and take up same memory space as a long long int data type, which ranges from 8 Bytes (i.e., 32 bits) to 16 Bytes (128 bits). It”s value ranges from 0 to (264-1). Syntax unsigned long long int variable_name; Example of int Data Type The following code shows the size and use of all derived int data types − #include <iostream> using namespace std; int main() { int a=16; short int b=3; long int c= -32; long long int d= 555; unsigned short int e=22; unsigned int f=33; unsigned long int g=888; unsigned long long int h=444444; cout << “sizeof int datatype is: ” << sizeof(a) <<” and the number is: “<<a<< endl; cout << “sizeof short int datatype is: “ << sizeof(unsigned int) <<” and the number is: “<<b<< endl; cout << “sizeof long int datatype is: “ << sizeof(short int) <<” and the number is: “<<c<< endl; cout << “sizeof long long int datatype is: “ << sizeof(unsigned short int) <<” and the number is: “<<d<< endl; cout << “sizeof unsigned short int datatype is: “ << sizeof(long int) <<” and the number is: “<<e<< endl; cout << “sizeof unsigned int datatype is: “ << sizeof(unsigned long int) <<” and the number is: “<<f<< endl; cout << “sizeof unsigned long int datatype is: “ << sizeof(long long int) <<” and the number is: “<<g<< endl; cout << “sizeof unsigned long long int datatype is: “ << sizeof(unsigned long long int) <<” and the number is: “<<h<< endl; return 0; } Output sizeof int datatype is: 4 and the number is: 16 sizeof short int datatype is: 4 and the number is: 3 sizeof long int datatype is: 2 and the number is: -32 sizeof long long int datatype is: 2 and the number is: 555 sizeof unsigned short int datatype is: 8 and the number is: 22 sizeof unsigned int datatype is: 8 and the number is: 33 sizeof unsigned long int datatype is: 8 and the number is: 888 sizeof unsigned long long int datatype is: 8 and the number is: 444444 float Data Type The float data type is used for floating-point elements, which are numbers that are followed by a decimal part. This data type takes 4 Bytes (i.e., 32 bits) of memory. Syntax float elem_name; Example of float Data Type The following code shows the size and use of all derived int data types − #include <bits/stdc++.h> using namespace std; int main() { float k=1.120123; cout << “sizeof float datatype is: “<<sizeof(k)<<” and the element is: “<<k<<endl; return 0; } Output sizeof float datatype is: 4 and the element is: 1.12012 double Data Type The double data type is used to store floating-point elements with double precision as compared to float. This data type takes 8 Bytes (i.e., 64 bits) of memory. Syntax double elem_name; The double data type

C++ Object Oriented

C++ Object Oriented ”; Previous Next The prime purpose of C++ programming was to add object orientation to the C programming language, which is in itself one of the most powerful programming languages. The core of the pure object-oriented programming is to create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an object which has certain properties such as color, number of doors, and the like. It also has certain methods such as accelerate, brake, and so on. There are a few principle concepts that form the foundation of object-oriented programming − Object This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled as a unit called as object. Class When you define a class, you define a blueprint for an object. This doesn”t actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object. Abstraction Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. For example, a database system hides certain details of how data is stored and created and maintained. Similar way, C++ classes provides different methods to the outside world without giving internal detail about those methods and data. Encapsulation Encapsulation is placing the data and the functions that work on that data in the same place. While working with procedural languages, it is not always clear which functions work on which variables but object-oriented programming provides you framework to place the data and the relevant functions together in the same object. Inheritance One of the most useful aspects of object-oriented programming is code reusability. As the name suggests Inheritance is the process of forming a new class from an existing class that is from the existing class called as base class, new class is formed called as derived class. This is a very important concept of object-oriented programming since this feature helps to reduce the code size. Polymorphism The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions is called polymorphism. Poly refers to many. That is a single function or an operator functioning in many ways different upon the usage is called polymorphism. Overloading The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made to operate on new data type, it is said to be overloaded. Print Page Previous Next Advertisements ”;

C++ Web Programming

C++ Web Programming ”; Previous Next What is CGI? The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows − The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, let”s see what happens when we click a hyperlink to browse a particular web page or URL. Your browser contacts the HTTP web server and demand for the URL ie. filename. Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file. Web browser takes response from web server and displays either the received file or error message based on the received response. However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display. The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc. CGI Architecture Diagram The following simple program shows a simple architecture of CGI − Web Server Configuration Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable. By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file − <Directory “/var/www/cgi-bin”> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> <Directory “/var/www/cgi-bin”> Options All </Directory> Here, I assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc. First CGI Program Consider the following C++ Program content − #include <iostream> using namespace std; int main () { cout << “Content-type:text/htmlrnrn”; cout << “<html>n”; cout << “<head>n”; cout << “<title>Hello World – First CGI Program</title>n”; cout << “</head>n”; cout << “<body>n”; cout << “<h2>Hello World! This is my first CGI program</h2>n”; cout << “</body>n”; cout << “</html>n”; return 0; } Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable. My First CGI program The above C++ program is a simple program which is writing its output on STDOUT file i.e. screen. There is one important and extra feature available which is first line printing Content-type:text/htmlrnrn. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood the basic concept of CGI and you can write many complicated CGI programs using Python. A C++ CGI program can interact with any other external system, such as RDBMS, to exchange information. HTTP Header The line Content-type:text/htmlrnrn is a part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form − HTTP Field Name: Field Content For Example Content-type: text/htmlrnrn There are few other important HTTP headers, which you will use frequently in your CGI Programming. Sr.No Header & Description 1 Content-type: A MIME string defining the format of the file being returned. Example is Content-type:text/html. 2 Expires: Date The date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT. 3 Location: URL The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file. 4 Last-modified: Date The date of last modification of the resource. 5 Content-length: N The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. 6 Set-Cookie: String Set the cookie passed through the string. CGI Environment Variables All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program. Sr.No Variable Name & Description 1 CONTENT_TYPE The data type of the content, used when the client is sending attached content to the server. For example file upload etc. 2 CONTENT_LENGTH The length of the query information that is available only for POST requests. 3 HTTP_COOKIE Returns the set cookies in the form of key & value pair. 4 HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. It is a name of the web browser. 5 PATH_INFO The path for the CGI script. 6 QUERY_STRING The URL-encoded information that is sent with GET method request. 7 REMOTE_ADDR The IP address of the remote host making the request. This can be useful for logging or for authentication purpose. 8 REMOTE_HOST The fully qualified name of the host making the request. If this information is not available then

C++ Date & Time

C++ Date and Time ”; Previous Next The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t, and tm. The types – clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer. The structure type tm holds the date and time in the form of a C structure having the following elements − struct tm { int tm_sec; // seconds of minutes from 0 to 61 int tm_min; // minutes of hour from 0 to 59 int tm_hour; // hours of day from 0 to 24 int tm_mday; // day of month from 1 to 31 int tm_mon; // month of year from 0 to 11 int tm_year; // year since 1900 int tm_wday; // days since sunday int tm_yday; // days since January 1st int tm_isdst; // hours of daylight savings time } Following are the important functions, which we use while working with date and time in C or C++. All these functions are part of standard C and C++ library and you can check their detail using reference to C++ standard library given below. Sr.No Function & Purpose 1 time_t time(time_t *time); This returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, .1 is returned. 2 char *ctime(const time_t *time); This returns a pointer to a string of the form day month year hours:minutes:seconds yearn. 3 struct tm *localtime(const time_t *time); This returns a pointer to the tm structure representing local time. 4 clock_t clock(void); This returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available. 5 char * asctime ( const struct tm * time ); This returns a pointer to a string that contains the information stored in the structure pointed to by time converted into the form: day month date hours:minutes:seconds yearn 6 struct tm *gmtime(const time_t *time); This returns a pointer to the time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT). 7 time_t mktime(struct tm *time); This returns the calendar-time equivalent of the time found in the structure pointed to by time. 8 double difftime ( time_t time2, time_t time1 ); This function calculates the difference in seconds between time1 and time2. 9 size_t strftime(); This function can be used to format date and time in a specific format. Current Date and Time Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same − Live Demo #include <iostream> #include <ctime> using namespace std; int main() { // current date/time based on current system time_t now = time(0); // convert now to string form char* dt = ctime(&now); cout << “The local date and time is: ” << dt << endl; // convert now to tm struct for UTC tm *gmtm = gmtime(&now); dt = asctime(gmtm); cout << “The UTC date and time is:”<< dt << endl; } When the above code is compiled and executed, it produces the following result − The local date and time is: Sat Jan 8 20:07:41 2011 The UTC date and time is:Sun Jan 9 03:07:41 2011 Format Time using struct tm The tm structure is very important while working with date and time in either C or C++. This structure holds the date and time in the form of a C structure as mentioned above. Most of the time related functions makes use of tm structure. Following is an example which makes use of various date and time related functions and tm structure − While using structure in this chapter, I”m making an assumption that you have basic understanding on C structure and how to access structure members using arrow -> operator. Live Demo #include <iostream> #include <ctime> using namespace std; int main() { // current date/time based on current system time_t now = time(0); cout << “Number of sec since January 1,1970 is:: ” << now << endl; tm *ltm = localtime(&now); // print various components of tm structure. cout << “Year:” << 1900 + ltm->tm_year<<endl; cout << “Month: “<< 1 + ltm->tm_mon<< endl; cout << “Day: “<< ltm->tm_mday << endl; cout << “Time: “<< 5+ltm->tm_hour << “:”; cout << 30+ltm->tm_min << “:”; cout << ltm->tm_sec << endl; } When the above code is compiled and executed, it produces the following result − Number of sec since January 1,1970 is:: 1588485717 Year:2020 Month: 5 Day: 3 Time: 11:31:57 Print Page Previous Next Advertisements ”;