Friday, 16 May 2014

C++ Date and Time

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

C++ Date and Time
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.
SNFunction & Purpose
1time_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.
2char *ctime(const time_t *time);
This returns a pointer to a string of the form day month year hours:minutes:seconds year\n\0.
3struct tm *localtime(const time_t *time);
This returns a pointer to the tm structure representing local time.
4clock_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.
5char * 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 year\n\0
6struct 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).
7time_t mktime(struct tm *time);
This returns the calendar-time equivalent of the time found in the structure pointed to by time.
8double difftime ( time_t time2, time_t time1 );
This function calculates the difference in seconds between time1 and time2.
9size_t strftime();
This function can be used to format date and time a specific format.

Current date and time:

Consider 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:
#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.
#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:" << 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: "<< 1 + ltm->tm_hour << ":";
cout
<< 1 + ltm->tm_min << ":";
cout
<< 1 + ltm->tm_sec << endl;
}
When the above code is compiled and executed, it produces the following result:
Number of sec since January 1, 1970:1294548238
Year: 2011
Month: 1
Day: 8
Time: 22: 44:59

Read more

C++ References

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

C++ References
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.

C++ References vs Pointers:

References are often confused with pointers but three major differences between references and pointers are:
  • You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
  • Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.
  • A reference must be initialized when it is created. Pointers can be initialized at any time.

Creating References in C++:

Think of a variable name as a label attached to the variable's location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example:
int    i = 17;
We can declare reference variables for i as follows.
int&    r = i;
Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer reference initialized to i" and read the second declaration as "s is a double reference initialized to d.". Following example makes use of references on int and double:
#include <iostream>

using namespace std;

int main ()
{
// declare simple variables
int i;
double d;

// declare reference variables
int& r = i;
double& s = d;

i
= 5;
cout
<< "Value of i : " << i << endl;
cout
<< "Value of i reference : " << r << endl;

d
= 11.7;
cout
<< "Value of d : " << d << endl;
cout
<< "Value of d reference : " << s << endl;

return 0;
}
When the above code is compiled together and executed, it produces the following result:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer:
ConceptDescription
References as parametersC++ supports passing references as function parameter more safely than parameters.
Reference as return valueYou can return reference from a C++ function like a any other data type can be returned.

Read more

C++ Pointers

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

C++ Pointers
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.
As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined:
#include <iostream>

using namespace std;

int main ()
{
int var1;
char var2[10];

cout
<< "Address of var1 variable: ";
cout
<< &var1 << endl;

cout
<< "Address of var2 variable: ";
cout
<< &var2 << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6

What Are Pointers?

pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:
int    *ip;    // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

Using Pointers in C++:

There are few important operations, which we will do with the pointers very frequently. (a) we define a pointer variables (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations:
#include <iostream>

using namespace std;

int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip
= &var; // store address of var in pointer variable

cout
<< "Value of var variable: ";
cout
<< var << endl;

// print the address stored in ip pointer variable
cout
<< "Address stored in ip variable: ";
cout
<< ip << endl;

// access the value at the address available in pointer
cout
<< "Value of *ip variable: ";
cout
<< *ip << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

C++ Pointers in Detail:

Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer:
ConceptDescription
C++ Null PointersC++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
C++ pointer arithmeticThere are four arithmetic operators that can be used on pointers: ++, --, +, -
C++ pointers vs arraysThere is a close relationship between pointers and arrays. Let us check how?
C++ array of pointersYou can define arrays to hold a number of pointers.
C++ pointer to pointerC++ allows you to have pointer on a pointer and so on.
Passing pointers to functionsPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
Return pointer from functionsC++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.

Read more

C++ Strings

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

C++ Strings
C++ provides following two types of string representations:
  • The C-style character string.
  • The string class type introduced with Standard C++.

The C-Style Character String:

The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write the above statement as follows:
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++:
String Presentation in C/C++
Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string:
#include <iostream>

using namespace std;

int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout
<< "Greeting message: ";
cout
<< greeting << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Greeting message: Hello
C++ supports a wide range of functions that manipulate null-terminated strings:
S.N.Function & Purpose
1strcpy(s1, s2);
Copies string s2 into string s1.
2strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3strlen(s1);
Returns the length of string s1.
4strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
Following example makes use of few of the above-mentioned functions:
#include <iostream>
#include <cstring>

using namespace std;

int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3
strcpy
( str3, str1);
cout
<< "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2
strcat
( str1, str2);
cout
<< "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation
len
= strlen(str1);
cout
<< "strlen(str1) : " << len << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows:
strcpy( str3, str1) : Hello
strcat
( str1, str2): HelloWorld
strlen
(str1) : 10

The String Class in C++:

The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. We will study this class in C++ Standard Library but for now let us check following example:
At this point, you may not understand this example because so far we have not discussed Classes and Objects. So can have a look and proceed until you have understanding on Object Oriented Concepts.
#include <iostream>
#include <string>

using namespace std;

int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;

// copy str1 into str3
str3
= str1;
cout
<< "str3 : " << str3 << endl;

// concatenates str1 and str2
str3
= str1 + str2;
cout
<< "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation
len
= str3.size();
cout
<< "str3.size() : " << len << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows:
str3 : Hello
str1
+ str2 : HelloWorld
str3
.size() : 10

Read more