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

Programming Code to Concatenate String

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
/* Programming Code to Concatenate String To concatenate or to append one string to another string in C++ Programming, you have to ask to the user to enter the two string and start concatenating one string into other using the strcat() function as shown here in the following program. Following C++ program ask the user to enter the two string to concatenate it using the function strcat() of string.h library. This function takes the two argument like strcat(str1, str2). Here string of str2 will be appended at the end of the string str1 : C++ Program - Concatenate String */ #include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> void main() { clrscr(); char str1[50], str2[50]; cout<<"Enter first string : "; gets(str1); cout<<"Enter second string : "; gets(str2); strcat(str1, str2); cout<<"String after concatenation is "<<str1; getch(); }
strcat() Function in C++
Concatenate strings. The strcat() function in C++ appends a copy of a string to the end of another string. It is defined in <cstring> header file. Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination. destination and source shall not overlap.
Syntax for strcat() Function in C++
#include <cstring> char * strcat ( char * destination, const char * source );
destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.
source
C string to be appended. This should not overlap destination. The strcat() function takes two arguments: destination and source. This function appends a copy of the character string pointed to by source to the end of string pointed to by destination. The null terminating character at the end of destination is replaced by the first character of source and the resulting character is also null terminated. destination is returned. The strcat() function returns destination, the pointer to the destination string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* append a copy of a string to the end of another string by strcat() function code example */ // CPP program to demonstrate strncat() function #include <cstring> #include <iostream> using namespace std; int main() { char dest[25] = "This is an example"; char src[50] = " to show working of strncat() this is not added"; strncat(dest, src, 29); cout << dest ; return 0; }
clrscr() Function in C++
It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.*/ #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); // use clrscr() after variable declaration sum=a+b; cout<<"Sum: "<<sum; //clear the console screen clrscr(); getch(); }
getch() Function in C++
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program.
Syntax for getch() Function in C++
#include <conio.h> int getch(void);
The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input. We use a getch() function in a C/ C++ program to hold the output screen for some time until the user passes a key from the keyboard to exit the console screen. Using getch() function, we can hide the input character provided by the users in the ATM PIN, password, etc. • getch() method pauses the Output Console until a key is pressed. • It does not use any buffer to store the input character. • The entered character is immediately returned without waiting for the enter key. • The entered character does not show up on the console. • The getch() method can be used to accept hidden inputs like password, ATM pin numbers, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* wait for any character input from keyboard by getch() function code example. The getch() function is very useful if you want to read a character input from the keyboard. */ // C code to illustrate working of // getch() to accept hidden inputs #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); sum=a+b; cout<<"Sum: "<<sum; getch(); // use getch() befor end of main() }
Standard Output Stream (cout) in C++
The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters. The << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
Strings in C++ Language
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).
Declaration for Strings in C++
char str[4] = "C++ Programming"; char str[] = {'C','+','+','\0'}; char str[4] = {'C','+','+','\0'};
In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings. C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0). • A character array is simply an array of characters that can be terminated by a null character. A string is a class that defines objects that be represented as a stream of characters. • The size of the character array has to be allocated statically, more memory cannot be allocated at run time if required. Unused allocated memory is wasted in the case of the character array. In the case of strings, memory is allocated dynamically. More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted. • There is a threat of array decay in the case of the character array. As strings are represented as objects, no array decay occurs. • Implementation of character array is faster than std:: string. Strings are slower when compared to implementation than character array. • Character arrays do not offer many inbuilt functions to manipulate strings. String class defines a number of functionalities that allow manifold operations on strings.
String Functions in C++
• int compare(const string& str): It is used to compare two string objects. • int length(): It is used to find the length of the string. • void swap(string& str): It is used to swap the values of two string objects. • string substr(int pos,int n): It creates a new string object of n characters. • int size(): It returns the length of the string in terms of bytes. • void resize(int n): It is used to resize the length of the string up to n characters. • string& replace(int pos,int len,string& str): It replaces portion of the string that begins at character position pos and spans len characters. • string& append(const string& str): It adds new characters at the end of another string object. • char& at(int pos): It is used to access an individual character at specified position pos. • int find(string& str,int pos,int n): It is used to find the string specified in the parameter. • int find_first_of(string& str,int pos,int n): It is used to find the first occurrence of the specified sequence. • int find_first_not_of(string& str,int pos,int n ): It is used to search the string for the first character that does not match with any of the characters specified in the string. • int find_last_of(string& str,int pos,int n): It is used to search the string for the last character of specified sequence. • int find_last_not_of(string& str,int pos): It searches for the last character that does not match with the specified sequence. • string& insert(): It inserts a new character before the character indicated by the position pos. • int max_size(): It finds the maximum length of the string. • void push_back(char ch): It adds a new character ch at the end of the string. • void pop_back(): It removes a last character of the string. • string& assign(): It assigns new value to the string. • int copy(string& str): It copies the contents of string into another. • char& back(): It returns the reference of last character. • Iterator begin(): It returns the reference of first character. • int capacity(): It returns the allocated space for the string. • const_iterator cbegin(): It points to the first element of the string. • const_iterator cend(): It points to the last element of the string. • void clear(): It removes all the elements from the string. • const_reverse_iterator crbegin(): It points to the last character of the string. • const_char* data(): It copies the characters of string into an array. • bool empty(): It checks whether the string is empty or not. • string& erase(): It removes the characters as specified. • char& front(): It returns a reference of the first character. • string& operator+=(): It appends a new character at the end of the string. • string& operator=(): It assigns a new value to the string. • char operator[](pos): It retrieves a character at specified position pos. • int rfind(): It searches for the last occurrence of the string. • iterator end(): It references the last character of the string. • reverse_iterator rend(): It points to the first character of the string. • void shrink_to_fit(): It reduces the capacity and makes it equal to the size of the string. • char* c_str(): It returns pointer to an array that contains null terminated sequence of characters. • const_reverse_iterator crend(): It references the first character of the string. • reverse_iterator rbegin(): It reference the last character of the string. • void reserve(inr len): It requests a change in capacity. • allocator_type get_allocator();: It returns the allocated object associated with the string.
Non-member Function Overloads
• operator+ Concatenate strings (function ) • relational operators Relational operators for string (function ) • swap Exchanges the values of two strings (function ) • operator>> Extract string from stream (function ) • operator<< Insert string into stream (function ) • getline Get line from stream into string (function )
Operators used for String Objects
• =: assignment • +: concatenation • ==: Equality • !=: Inequality • <: Less than • <=: Less than or equal • >: Greater than • >=: Greater than or equal • []: Subscription • <<: Output • >>: Input
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 38 39
/* C++ String Library */ /* The C-Style Character String */ // C++ Program to demonstrate the working of getline(), push_back() and pop_back() #include <iostream> #include <string> // for string class using namespace std; // Driver Code int main() { // Declaring string string str; // Taking string input using getline() getline(cin, str); // Displaying string cout << "The initial string is : "; cout << str << endl; // Inserting a character str.push_back('s'); // Displaying string cout << "The string after push_back operation is : "; cout << str << endl; // Deleting a character str.pop_back(); // Displaying string cout << "The string after pop_back operation is : "; cout << str << endl; 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
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
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; }
#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; }
gets() Function in C++
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
Syntax for gets() Function in C++
#include <cstdio> char * gets ( char * str );
str
Pointer to a block of memory (array of char) where the string read is copied as a C string. On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed). The most recent revision of the C standard (2011) has definitively removed this function from its specification. The function is deprecated in C++ (as of 2011 standard, which follows C99+TC3).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* The gets() function in C++ reads characters from stdin and stores them until a newline character is found or end of file occurs. */ /* Get string from stdin by gets() function code example */ //Program demonstrating the difference between gets and cin #include<iostream.h> #include<stdio.h> int main() { char str1[80],str2[80]; cout<<"\n Enter a string using gets(): "; gets(str1); cout<<"\n Enter a string using cin object: "; cin>>str2; cout<<"\n String input with gets(): "; cout<<str1; cout<<"\n String input with cin object: "; cout<<str2; return 0; }


Full form of Ascii is American Standard Code for Information Interchange. It is a character "Encoding Scheme". Originally based on the English alphabet, every character or number
In this control structure we have only one 'if' and one 'else', however we can have multiple 'else if' blocks. This is how it looks: If none of the 'condition is true' then these statements
Program ask to the user to enter any two 3*3 array elements to subtract them i.e., Matrix1 - Matrix2, then display the "subtracted" result of the two matrices ( Matrix3 ) on the screen:
Number of bits in the Bloom filter. Number of bits set per Mapping in Filter. Table of "8-bit" CRC32 remainders. Bloom filter array of M/8 bytes. Number of bytes in Bloom filter. Main