Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Data Structures and Algorithm Analysis in C++ Code Examples

If you don't have a string type

/* If you don't have a string type */ #include <string.h> #include "mystring.h" string::string( const char * cstring ) { if( cstring == NULL ) cstring = ""; strLength = strlen( cstring ); bufferLength = strLength + 1; buffer = new char[ bufferLength ]; strcpy( buffer, cstring ); } string::string( const string & str ) { strLength = str.length( ); bufferLength = strLength + 1; buffer = new char[ bufferLength ]; strcpy( buffer,str.buffer ); } const string & string::operator=( const string & rhs ) { if( this != &rhs ) { if( bufferLength < rhs.length( ) + 1 ) { delete [ ] buffer; bufferLength = rhs.length( ) + 1; buffer = new char[ bufferLength ]; } strLength = rhs.length( ); strcpy( buffer, rhs.buffer ); } return *this; } const string & string::operator+=( const string & rhs ) { if( this == &rhs ) { string copy( rhs ); return *this += copy; } int newLength = length( ) + rhs.length( ); if( newLength >= bufferLength ) { bufferLength = 2 * ( newLength + 1 ); char *oldBuffer = buffer; buffer = new char[ bufferLength ]; strcpy( buffer, oldBuffer ); delete [ ] oldBuffer; } strcpy( buffer + length( ), rhs.buffer ); strLength = newLength; return *this; } char & string::operator[ ]( int k ) { if( k < 0 || k >= strLength ) throw StringIndexOutOfBounds( ); return buffer[ k ]; } char string::operator[ ]( int k ) const { if( k < 0 || k >= strLength ) throw StringIndexOutOfBounds( ); return buffer[ k ]; } ostream & operator<<( ostream & out, const string & str ) { return out << str.c_str(); } istream & operator>>( istream & in, string & str ) { char buf[ string::MAX_LENGTH + 1 ]; in >> buf; if( !in.fail( ) ) str = buf; return in; } istream & getline( istream & in, string & str ) { char buf[ string::MAX_LENGTH + 1 ]; in.getline( buf, string::MAX_LENGTH ); if( !in.fail( ) ) str = buf; return in; } bool operator==( const string & lhs, const string & rhs ) { return strcmp( lhs.c_str( ), rhs.c_str( ) ) == 0; } bool operator!=( const string & lhs, const string & rhs ) { return strcmp( lhs.c_str( ), rhs.c_str( ) ) != 0; } bool operator<( const string & lhs, const string & rhs ) { return strcmp( lhs.c_str( ), rhs.c_str( ) ) < 0; } bool operator<=( const string & lhs, const string & rhs ) { return strcmp( lhs.c_str( ), rhs.c_str( ) ) <= 0; } bool operator>( const string & lhs, const string & rhs ) { return strcmp( lhs.c_str( ), rhs.c_str( ) ) > 0; } bool operator>=( const string & lhs, const string & rhs ) { return strcmp( lhs.c_str( ), rhs.c_str( ) ) >= 0; }

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

Check whether either failbit or badbit is set. Returns true if either (or both) the failbit or the badbit error state flags is set for the stream. At least one of these flags is set when an error occurs during an input operation. failbit is generally set by an operation when the error is related to the internal logic of the operation itself; further operations on the stream may be possible. While badbit is generally set when the error involves the loss of integrity of the stream, which is likely to persist even if a different operation is attempted on the stream. badbit can be checked independently by calling member function bad. This function does not accept any parameter. Function returns true if badbit and/or failbit are set.

Allocate storage space. Default allocation functions (single-object form). A new operator is used to create the object while a delete operator is used to delete the object. When the object is created by using the new operator, then the object will exist until we explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related to the block structure of the program.

Strings are objects that represent sequences of characters. The standard string class provides support for such objects with an interface similar to that of a standard container of bytes, but adding features specifically designed to operate with strings of single-byte characters. The string class is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type, with its default char_traits and allocator types. Note that this class handles bytes independently of the encoding used: If used to handle sequences of multi-byte or variable-length characters (such as UTF-8), all members of this class (such as length or size), as well as its iterators, will still operate in terms of bytes (not actual encoded characters).

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:

Return length of string. Returns the length of the string, in terms of bytes. This function is used to find the length of the string in terms of bytes. This is the actual number of bytes that conform the contents of the string , which is not necessarily equal to the storage capacity. This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity. Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).

Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source. strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. It copies the whole string to the destination string. It replaces the whole string instead of appending it. It won't change the source string.

Get string length. Returns the length of the C string str. C++ strlen() is an inbuilt function that is used to calculate the length of the string. It is a beneficial method to find the length of the string. The strlen() function is defined under the string.h header file. The strlen() takes a null-terminated byte string str as its argument and returns its length. The length does not include a null character. If there is no null character in the string, the behavior of the function is undefined.

Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:

Get line from stream into string. The cin is an object which is used to take input from the user but does not allow to take the input in multiple lines. To accept the multiple lines, we use the getline() function. It is a pre-defined function defined in a <string.h> header file used to accept a line or a string from the input stream until the delimiting character is encountered. Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)). The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation. If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

Compare two strings. Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll. The strcmp() function in C++ compares two null-terminating strings (C-strings). The comparison is done lexicographically. It is defined in the cstring header file.

Get C string equivalent. Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end. This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end. This function does not accept any parameter. Function returns a pointer to the c-string representation of the string object's value.

The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable.

Deallocate storage space. Default deallocation functions (single-object form). A delete operator is used to deallocate memory space that is dynamically created using the new operator, calloc and malloc() function, etc., at the run time of a program in C++ language. In other words, a delete operator is used to release array and non-array (pointer) objects from the heap, which the new operator dynamically allocates to put variables on heap memory. We can use either the delete operator or delete [ ] operator in our program to delete the deallocated space. A delete operator has a void return type, and hence, it does not return a value.

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer. In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++: • It can be used to pass current object as a parameter to another method. • It can be used to refer current class instance variable. • It can be used to declare indexers. To understand 'this' pointer, it is important to know how objects look at functions and data members of a class.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

The digit sum of a given integer is the sum of all its digits (digit sum of '84001' is calculated as 8+4+0+0+1 = 13). Odd number is an integer which is not a multiple of two. If it is "divided"







A C++ Program to genrate random numbers using Naor-Reingold random function. Moni Naor and Omer Reingold described efficient constructions for cryptographic primitives in

To convert "Hexadecimal" number to "binary" number in C++, you have to ask to the user to enter the hexadecimal number to convert it into binary number to display the equivalent

To sort an array in ascending order by bubble sort in C++ language, you have to ask to user to enter the array size then ask to enter array elements, start sorting the array elements by