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++ > Code Snippets Code Examples

Using Binary I/O with Array-Based Streams

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Using Binary I/O with Array-Based Streams */ #include <iostream> #include <strstream> using namespace std; int main() { char *p = "this is a test\1\2\3\4\5\6\7"; istrstream ins(p); char ch; while (!ins.eof()) { // read and display binary info ins.get(ch); cout << hex << (int) ch << ' '; } return 0; }
#include Directive in C++
#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.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
IOS Library eof() Function in C++
Check whether eofbit is set. Returns true if the eofbit error state flag is set for the stream. This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream. Note that the value returned by this function depends on the last operation performed on the stream (and not on the next). Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.
Syntax for IOS eof() Function in C++
bool eof() const;
This function does not accept any parameter. Function returns true if the stream's eofbit error state flag is set (which signals that the End-of-File has been reached by the last input operation). false otherwise.
Data races
Accesses the stream object. Concurrent access to the same stream object may cause data races.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* The eof() method of ios class in C++ is used to check if the stream is has raised any EOF (End Of File) error. It means that this function will check if this stream has its eofbit set. */ // C++ code example to demonstrate the working of eof() function #include <iostream> #include <fstream> int main () { std::ifstream is("example.txt"); char c; while (is.get(c)) std::cout << c; if (is.eof()) std::cout << "[EoF reached]\n"; else std::cout << "[error reading]\n"; is.close(); return 0; }
What is an Array in C++ Language
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations. By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.
Properties of Array
The array contains the following properties. • Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes. • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. • Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
Advantage of C++ Array
• 1) Code Optimization: Less code to the access the data. • 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. • 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. • 4) Random Access: We can access any element randomly using the array.
Disadvantage of C++ Array
• 1) Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C++ is not dynamic. • 2) Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
Declaration of C++ Array
To declare an array in C++, a programmer specifies the type of the elements and the number of elements required by an array as follows
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C++ either one by one or using a single statement as follows
double balance[5] = {850, 3.0, 7.4, 7.0, 88};
The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write
double balance[] = {850, 3.0, 7.4, 7.0, 88};
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array.
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* arrays in C++ Language */ #include <iostream> using namespace std; int main() { // initialize an array without specifying size double numbers[] = {7, 5, 6, 12, 35, 27}; double sum = 0; double count = 0; double average; cout << "The numbers are: "; // print array elements // use of range-based for loop for (const double &n : numbers) { cout << n << " "; // calculate the sum sum += n; // count the no. of array elements ++count; } // print the sum cout << "\nTheir Sum = " << sum << endl; // find the average average = sum / count; cout << "Their Average = " << average << endl; return 0; }
Namespaces in C++ Language
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code. A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name { // code declarations }
To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows:
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files. So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name { // code declarations }
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } }
• Namespace is a feature added in C++ and not present in C. • A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. • Namespace declarations appear only at global scope. • Namespace declarations can be nested within another namespace. • Namespace declarations don't have access specifiers. (Public or private) • No need to give semicolon after the closing brace of definition of namespace. • We can split the definition of namespace over several units.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/* namespaces in C++ language */ // A C++ code to demonstrate that we can define // methods outside namespace. #include <iostream> using namespace std; // Creating a namespace namespace ns { void display(); class happy { public: void display(); }; } // Defining methods of namespace void ns::happy::display() { cout << "ns::happy::display()\n"; } void ns::display() { cout << "ns::display()\n"; } // Driver code int main() { ns::happy obj; ns::display(); obj.display(); return 0; }
While Loop Statement in C++
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
Syntax for While Loop Statement in C++
while (condition) { // body of the loop }
• A while loop evaluates the condition • If the condition evaluates to true, the code inside the while loop is executed. • The condition is evaluated again. • This process continues until the condition is false. • When the condition evaluates to false, the loop terminates. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* While Loop Statement in C++ language */ // program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include <iostream> using namespace std; int main() { int number; int sum = 0; // take input from the user cout << "Enter a number: "; cin >> number; while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << "Enter a number: "; cin >> number; } // display the sum cout << "\nThe sum is " << sum << endl; return 0; }
Return Statement in C++
A return statement ends the processing of the current function and returns control to the caller of the function. A value-returning function should include a return statement, containing an expression. If an expression is not given on a return statement in a function declared with a non-void return type, the compiler issues an error message. If the data type of the expression is different from the function return type, conversion of the return value takes place as if the value of the expression were assigned to an object with the same function return type.
Syntax for Return Statement in C++
For a function of return type void, a return statement is not strictly necessary. If the end of such a function is reached without encountering a return statement, control is passed to the caller as if a return statement without an expression were encountered. In other words, an implicit return takes place upon completion of the final statement, and control automatically returns to the calling function. If a return statement is used, it must not contain an expression. The following are examples of return statements:
return; /* Returns no value */ return result; /* Returns the value of result */ return 1; /* Returns the value 1 */ return (x * x); /* Returns the value of x * x */
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* illustrate Methods returning a value using return statement in C++ code example */ #include <iostream> using namespace std; // non-void return type // function to calculate sum int SUM(int a, int b) { int s1 = a + b; // method using the return // statement to return a value return s1; } // Driver method int main() { int num1 = 10; int num2 = 10; int sum_of = SUM(num1, num2); cout << "The sum is " << sum_of; return 0; }
Iostream Library get() Function in C++
Get characters. Extracts characters from the stream, as unformatted input. The get() function is used to read a character(at a time) from a file. The classes istream and ostream define two member functions get(), put() respectively to handle the single character input/output operations. There are two types of get() functions. Both get(char *) and get(void) prototype can be used to fetch a character including the blank space,tab and newline character. The get(char *) version assigns the input character to its argument and the get(void) version returns the input character. Since these functions are members of input/output Stream classes, these must be invoked using appropriate objects.
Syntax for get() Function in C++
#include <iostream> //single character (1) int get(); istream& get (char& c); //c-string (2) istream& get (char* s, streamsize n); istream& get (char* s, streamsize n, char delim); //stream buffer (3) istream& get (streambuf& sb); istream& get (streambuf& sb, char delim);
The reference to a character where the extracted value is stored.
Pointer to an array of characters where extracted characters are stored as a c-string. If the function does not extract any characters (or if the first character extracted is the delimiter character) and n is greater than zero, this is set to an empty c-string.
Maximum number of characters to write to s (including the terminating null character). If this is less than 2, the function does not extract any characters and sets failbit. streamsize is a signed integral type.
Explicit delimiting character: The operation of extracting successive characters stops as soon as the next character to extract compares equal to this.
A streambuf object on whose controlled output sequence the characters are copied. • (1) single character Extracts a single character from the stream. The character is either returned (first signature), or set as the value of its argument (second signature). • (2) c-string Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or the delimiting character is encountered: the delimiting character being either the newline character ('\n') or delim (if this argument is specified). The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character). A null character ('\0') is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted. • (3) stream buffer Extracts characters from the stream and inserts them into the output sequence controlled by the stream buffer object sb, stopping either as soon as such an insertion fails or as soon as the delimiting character is encountered in the input sequence (the delimiting character being either the newline character, '\n', or delim, if this argument is specified). Only the characters successfully inserted into sb are extracted from the stream: Neither the delimiting character, nor eventually the character that failed to be inserted at sb, are extracted from the input sequence and remain there as the next character to be extracted from the stream. The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before meeting the conditions described above), the function sets the eofbit flag. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning. The number of characters successfully read and stored by this function can be accessed by calling member gcount. The first signature returns the character read, or the end-of-file value (EOF) if no characters are available in the stream (note that in this case, the failbit flag is also set). All other signatures always return *this. Note that this return value can be checked for the state of the stream (see casting a stream to bool for more info). Errors are signaled by modifying the internal state flags: • eofbit The function stopped extracting characters because the input sequence has no more characters available (end-of-file reached). • failbit Either no characters were written or an empty c-string was stored in s. • badbit Error on stream (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected. Multiple flags may be set by a single operation. If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Modifies c, sb or the elements in the array pointed by s. Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream object cin when this is synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which extracted characters are attributed to threads).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state. Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/* reads a single character from the associated stream by get() function code example. */ /* It is used to fetch a character from the file and continues to do so until the end-of-the file condition is reached. */ //C++ Reading the content to a file using ifstream class and file mode ios::in #include<iostream> #include<ifstream> using namespace std; int main() { //Creating an input stream to read a file ifstream ifstream_ob; //Opening a file named File1.txt to read its content ifstream_ob.open("File1.txt", ios::in); char ch; //Reading the file using get() function and displaying its content while(ifstream_ob) { ch = ifstream_ob.get(); cout<<ch; } //Closing the input strea ifstream_ob.close(); return 0; }
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main() { ............ ............ }
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }

Program accepts "coefficients" of a quadratic equation from the user and displays the roots (both real and complex roots depending upon the discriminant). 'ax^2+bx+c = 0' (where a, b,