Character in C++
Introduction to Characters:
In programming, characters assume a vital part as they structure the establishment for working with printed information. In C++, characters are addressed utilizing the char data type. Understanding characters is fundamental for assignments from handling individual images to working with whole text strings. A Char is a C++ information type utilized for storing letters, digits, punctuation marks and special characters like spaces or tabs. C++ char is an integral data type, meaning the worth is put away as a whole number.
Char Data Type:
In C++, the char data type is utilized to address individual characters. It is an
Essential data type that distributes memory to hold a solitary character. The char type is unimaginably flexible and fills in as the structure block for making strings, which are groupings of characters.
At the point when a character is put away in memory, it is dispensed a limited quantity of space, normally one byte. This is adequate to hold the mathematical portrayal of the person in light of the ASCII (American Standard Code for Information Interchange) or Unicode encoding standards.
Characters are the groundwork of literary textual data processing in programming. They empower assignments like perusing client input, controlling strings, and performing procedures on individual characters. Understanding characters is vital for many applications, from essential control centre projects to text processing algorithms.
Importance of char in C++:
The char data type stands firm on a critical footing in C++ programming
because of its basic job in dealing with textual information.
- Text Processing: char considers the portrayal and control of individual characters. This structures the reason for dealing with text, a crucial part of various applications.
- File Operations: Perusing from and writing to documents frequently includes char data. It works with the perusing and composing of text-based data to external files.
- String Operations: Characters act as the structure blocks for strings.
Understanding char is fundamental for assignments like concatenation, comparison, and manipulation of strings.
4. Efficient Memory Usage: Being possible for the smallest data types, char helps in productive memory utilization. It is especially significant while managing a lot of textual information.
5. User Input Handling: While managing user interactions, particularly in console applications, char is utilized to catch single-character inputs. This is urgent in making interactive programs.
- Char in C++ also helps in Character Classification, Integration with Libraries, Algorithms and Data Structures, Portability and Interoperability, and it is the Foundation for Other Data Types.
- Characters are often used as the basis for defining custom data types, such as creating specialized data structures or encoding schemes.
Declaration and Initialization of char variables:
In C++, the char data type is utilized to address individual characters. It can hold any character from the character set, including letters, digits, punctuation marks and special symbols. It is constantly encased inside a single quote (' '). Let us see the various ways to initialize and declare the char variables in C++:
Syntax:
char variable_name;
Example:
#include <iostream>
using namespace std;
int main()
{
char character=k
cout << character;
return 0;
}
Output:
Explanation;
- #include <iostream>, this line incorporates the header document <iostream>, which contains announcements for the cin, cout, and other stream objects utilized for input operations and output operations.
- #Using namespace std, this line is a utilizing directive. It lets the compiler know we'll utilize names from the standard namespace. This permits us to utilize standard library functions and objects like cout without indicating std before them.
- Int main(), this is the passage point of the C++ program. Int indicates that the main function returns a number. The main function is where the program begins its execution.
- Char character = 'k'; this line proclaims a variable named character of type char and introduces it with the character 'k'. This implies that the character will hold the ASCII worth of the character 'k', 107.
- cout << character, this line utilizes the cout object, which is important for the std namespace and permits us to yield data to the console. It prints the worth of the character to the console.
- return 0, and this assertion shows that the main function has finished effectively. In C++, returning 0 from the main function normally demonstrates that the program has ended with practically no errors.
ASCII and Unicode Representation:
Characters are inside addressed utilizing mathematical codes. The ASCII standard relegates a unique value to each character, ranging from 0 to 127, permitting PCs to comprehend and handle text. Unicode, then again, is a more thorough encoding framework that covers a more extensive scope of characters, including those from different dialects and special symbols.
Example: ASCII code for ‘a’ is 97
The ASCII code for 'A' is 65
ASCII code for ‘@’ is 64 like this for every letter; special symbols have defined ASCII values.
Printing ASCII Value:
As we have seen, each character is deciphered as an ASCII character. It's workable for you to get the ASCII value for each and every character. Simply, it is implemented by passing the character to the int() function. This method is called as typecasting. It can be implemented as:
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char character;
cout << "Enter the input character: ";
cin >> character;
cout << "The ASCII Value of the input character " << character << " is "
<< int(character);
return 0;
}
Output:
Explanation:
- Counting the iostream header record into our code to utilize its capabilities.
- Inserting the std namespace into our code to utilize std namespace classes without calling it.
- Calling the main() function. The program logic ought to be added inside the body of the main function.
- Proclaim a char variable named character.
- Print some text on the console. The text requests that the client enter an incentive for the variable character.
- Peruse the client input from the console and store it in the variable character.
- Print some text on the console. The text will incorporate the person you entered for the variable character, the ASCII value of this character, and other text.
- The program should return esteem upon effective finishing.
Printing Char from ASCII Value:
For a given ASCII value, the C++ compiler can return the related character. When we declare a char variable and dole out a whole number worth. It will be switched over completely to the related character value.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char p = 64;
char q = 76;
char r = 110;
cout << p;
cout << q;
cout << r;
return 0;
}
The above program is also written by initializing multiple char values in a single line, i.e.,
#include <iostream>
using namespace std;
int main()
{
char p = 64, q = 76, r = 110;
cout << p;
cout << q;
cout << r;
return 0;
}
Output:
Inputting Chars:
We can utilize the std::cin function to peruse a char the client enters through the console. The std::cin will permit you to enter many characters. Nonetheless, the character variable can hold just a single character. This implies just the main character entered will be disengaged and put away in the character variable. The rest will stay in the console buffer utilized by std::cin. Making subsequent calls to the std::in function, it can be separated.
Example:
Program:
#include <iostream>
using namespace std;
int main() {
cout << "Enter the sequence of characters: ";
char character;
cin >> character;
cout <<"The ASCII code of "<< character << " is "<< int(character) <<
'\n';
cin >> character;
cout <<"The ASCII code of " << character << " is "<< int(character) <<
'\n';
cin >> character;
cout <<"The ASCII code of " << character << " is "<< int(character) <<
'\n';
return 0;
}
Output:
- Here, when we read input from the console, the input will be put away in the variable character. Since the user will type a character sequencing like "$Wb?pa", the first character, '$', will be put away in the variable character.
- Printing the first character entered in the console, its ASCII code and also other text in the console. The ASCII code is set by passing the character variable into the int() function.
- Peruse the following character that was placed by the user. The client will not be expected to enter another character. It will rather peruse the second character that was placed, which is 'W.'
- Printing the subsequent character entered its ASCII code and other text on the console. The ASCII code is set by passing the variable name (character) into the int() function.
- Then, the program will return a value after compiling the program without any errors.
Char Operations in C++:
In C++, characters (type char) are treated as little whole numbers addressing ASCII values. This permits you to perform different operations on characters utilizing arithmetic and logical operations.
Character arithmetic is utilized to execute arithmetic operations like addition, multiplication, subtraction and division on characters in C++ language. In character, arithmetic operations switch into integer value completely to perform the task. For this, ASCII values are utilized. It is mainly used to perform the actions on the strings.
Arithmetic Operations:
1.Addition Operation:
Example 1:
Program:
#include <iostream>
using namespace std;
int main()
{
char char1 = 2, char2 = 120;
char1 = char1 + char2;
cout << static_cast<int>(ch1) << endl;
return 0;
}
Output:
Example 2:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch1 = 10, ch2 = 120;
ch1 = ch1 + ch2;
cout << static_cast<int>(ch1) << endl;
return 0;
}
Output:
- When performing the addition operation in the second example, we got '-126' because when the output value exceeds 128, it will give a negative symbol in the output. From the above example, the addition of 120 and 10 is 130, but actually, it is limited to 128 only, as the difference between 130 and 128 is '2'. So, the output will be 128 – 2, indicated with a negative sign.
2. Subtraction Operation:
Example 1:
Program:
#include <iostream>
using namespace std;
int main()
{
char char1 = 125, char2 = 10;
char1 = char1 + char2;
cout << static_cast < int > (char1 - char2 - 7) << endl;
return 0;
}
Output:
Example 2:
Program:
#include <iostream>
using namespace std;
int main()
{
char char1 = 125, char2 = 10;
char1 = char1 + char2;
cout << static_cast < char > (char1 - char2 - 7) << endl;
return 0;
}
Output:
- In the Subtraction operation, if we observe that both the codes are the same, but the difference is that in line 8, if we want to get the output as an integer value, then we mention "int", or else, if we want the output as a character then we mention as "char". So, in this way, we can get our required output either as an integer or as a character.
Example:
Program:
#include <bits/stdc++.h>
using namespace std;
int main(){
char v1 = 'j';
char v2 = 't';
char v3 = 'p';
char n1 = v1 + 3;
char n2 = v2 - 1;
char n3 = v3 + 2;
cout<<"Numerical value = "<<(int)n1<<endl;
cout<<"Numerical value = "<<(int)n2<<endl;
cout<<"Character = "<<(char)n3<<endl;
return 0;
}
Output:
3.Increment and Decrement Operations:
Increment and Decrement operations are used to either increase or decrease the given input by the value '1'. The increment operator will increase the value by 1, and the decrement operator will decrease the value by 1, which is similar to the addition and subtraction operations, respectively. But the key difference is that in addition and subtraction, we can increase (or) decrease the value by any number, but in increment and decrement operations, the value is increased by only one.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch1 = 'J';
char ch2 = ch1 + 1;
char ch3 = ch2 - 1;
cout << static_cast<char>(ch2) << endl;
cout << static_cast<char>(ch3) << endl;
cout << static_cast<int>(ch2) << endl;
cout << static_cast<int>(ch3) << endl;
return 0;
}
Output:
4. Comparison Operations:
Comparison Operations is mainly used to compare any two characters with their ASCII values. But here, we cannot modify the character pre-defined value; it will just compare whether the two values are equal or not (or) which value is greater and which value is lesser among those two numbers.
Example 1:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch1 = '@';
char ch2 = '#';
if (ch1 == ch2) {
cout << "ch1 and ch2 both are equal" << endl;
}
else {
cout << "ch1 is not equal to ch2" << endl;
}
return 0;
}
Output:
Example 2:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch1 = 'K';
char ch2 = 'S';
if (ch1 > ch2) {
cout << " ch1 is greater than ch2 " << endl;
}
else {
cout << " ch1 is less than ch2 " << endl;
}
return 0;
}
Output:
Conclusion:
We can say that the comparison operators play a crucial role in assessing connections between factors. They permit us to decide on balance, imbalance, and relative order between the values. Using ==, !=, <, >, <=, and >=, we can pursue logical choices inside our programs. These operators are vital apparatuses for controlling the program flow and executing conditional logic. By understanding how to utilize comparison operators, one can compose more flexible and robust program.
Logical Operators:
In C++ programming language (or) any other programming language, logical operators are the symbols that permit you to modify or combine conditions to make some logical evaluations. They are utilized to perform logical operations on the Boolean values (true or false).
In C++ programming language, we can perform the following logical operators for the given character.
- Logical NOT
- Logical AND
- Logical OR
1.Logical AND (&&) Operation:
The logical AND operator (&&) is a principal idea in Boolean algebra and programming. It is utilized to join at least two circumstances and produces an outcome that is true if all the provided circumstances are true. Otherwise, it will provide false.
Truth Table:
Operand A | Operand B | A && B |
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Example 1:
Program:
#include <iostream>
int main() {
bool val1 = false;
bool val2 = false;
bool res = val1 && val2;
std::cout << "Result : " << std::boolalpha << res << std::endl;
return 0;
}
Output:
Example 2:
Program:
#include <iostream>
int main() {
char grade;
grade = 'B';
if (grade == 'O' && grade != 'F') {
std::cout << "Congratulations! You have passed" << std::endl;
}
else {
std::cout << "You have either failed, or you did not get 'O' grade" << std::endl;
}
return 0;
}
Output:
2.Logical OR (||) Operation:
The logical OR operator (||) is a principal idea in Boolean algebra and programming. It is utilized to join at least two circumstances and produces an outcome that is true if any of the provided circumstances are true. Otherwise, it will provide false.
Truth Table:
Operand A | Operand B | A || B |
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Example 1:
Program:
#include <iostream>
int main() {
bool val1 = true;
bool val2 = false;
bool res = val1 || val2;
std::cout << "Result : " << std::boolalpha << res << std::endl;
return 0;
}
Output:
Example 2:
Program:
#include <iostream>
int main() {
char grade;
grade = 'B';
if (grade == 'O' || grade != 'F') {
std::cout << "Congratulations! You have passed" << std::endl;
}
else {
std::cout << "You have failed" << std::endl;
}
return 0;
}
Output:
3.Logical NOT (!) Operation:
The logical NOT operator is denoted by ‘!’; it is a unary operator that refutes the value of a Boolean articulation. This operand is utilized to negate the logical state of the given operator. As such, in this case, if a condition is true, applying the logical NOT operator will provide a false. Similarly, if the condition is false, applying the logical NOT operator will provide true, which is vice versa.
Truth Table:
Operand 1 | Result |
True | False |
False | True |
Syntax:
! expression
Example 1:
Program:
#include <iostream>
int main() {
bool my_bool = true;
bool res = !my_bool;
std::cout << std::boolalpha;
std::cout << "my_bool is: " << my_bool << std::endl;
std::cout << "Result of !my_bool is: " << res << std::endl;
return 0;
}
Output:
Example 2:
Program:
#include <iostream>
using namespace std;
int main() {
bool isStudying = true;
bool isNotStudying = !isStudying;
cout << "Is she Studying? " << (isStudying ? "Yes" : "No") << endl;
cout << "Is she not Studying? " << (isNotStudying ? "Yes" : "No") << endl;
return 0;
}
Output:
Conclusion:
Logical Operators in programming language empower you to consolidate conditions and make expressive logic. Also, they are significant while working with decision-making and controlling the flow of a program. The logical AND (&&) operator guarantees that a condition is valid for the two operands prior to executing a block of code. The logical OR (||) operator permits the execution of a block of code on the off chance that something like one condition is valid. The logical NOT (!) operator nullifies the consequence of a condition, switching its truth value.
Type Casting:
Type Casting in C++ programming is the most common way of changing over one data type into another data type. This can be especially valuable when you need to perform tasks or operations, including different variables. There are four kinds of type Casting in C++. They are:
- Static cast operator
- Dynamic cast operator
- Const cast operator
- Reinterpret cast operator
1.Static cast operator:
Static cast can perform transformations between pointers to related classes, not just from the determined (or) derived class to its base, but additionally from a base class to its inferred. This guarantees that, basically, the classes are viable if the proper object is changed over. Yet, no security check is performed during runtime to check assuming that the object being changed over is, as a matter of fact, a full object of the destination type. Subsequently, it really depends on the developer to guarantee that the change is protected. On the opposite side, the above of the type safety checks of dynamic cast is being avoided or not. Static cast operators are used for both implicit and explicit conversions.
Syntax:
static_cast<new_datatype>(input_value)
- Here, ‘new_datatype’ is the required data type that we need to convert and the 'input_value’ is the value (or) expression we need to convert.
- The static cast can be utilized to convert between the related types, like numeric types or pointers in the same inheritance hierarchy.
Example:
Program:
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int number = 15;
double numberDouble = static_cast<double>(number);
cout << typeid(number).name() << endl;
cout << typeid(static_cast<double>(number)).name() << endl;
cout << typeid(numberDouble).name() << endl;
return 0;
}
Output:
Explanation:
- In the above example, we have incorporated the "typeinfo" library with the goal that we can utilize the typeid() function to check the data type. We have characterized a number variable 'number' and changed over it double utilizing “static_cast”. From that point forward, we print the data types of variables and pass “static_cast <double> (number)” in typeid() function to check its data type.
- We can see the result as "i, d, d" is printed where 'i' means number and 'd' signifies "double". Hence, in the above example, integer is changed into "double".
2. Dynamic cast operator:
The dynamic cast operator is the mostly used to perform downcasting (changing over a pointer/reference of a base class to a determined (or) the derived class). It guarantees type safety by playing out a runtime check to confirm the legitimacy of the conversion. Its motivation is to guarantee that the consequence of the sort of change is a legitimate total object of the requested class.
Syntax:
dynamic_cast <new_datatype> (input_value);
- Here, ‘new_datatype' is the required data type that we need to convert and the 'input_value’ is the value (or) expression we need to convert.
- In dynamic cast, if conversion of the expression is not possible, then it will return a null pointer (for the pointer conversions), or it will throw a bad cast for reference conversions. We can say that the dynamic cast is always effective when we cast a class to one of its base classes.
Example:
Program:
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() const
{
cout << "Animal speaking" << endl;
}
};
class Dog : public Animal {
public:
void speak() const override
{
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void speak() const override
{
cout << "Cat meows." << endl;
}
};
int main()
{
Animal* animalPtr = new Dog();
Dog* dogPtr = dynamic_cast<Dog*>(animalPtr);
if (dogPtr) {
dogPtr->speak();
}
else {
cout << "Failed to cast the Dog." << endl;
}
Cat* catPtr = dynamic_cast<Cat*>(animalPtr);
if (catPtr) {
catPtr->speak();
}
else {
cout << "Failed to cast the Cat." << endl;
}
delete animalPtr;
return 0;
}
Output:
Explanation:
- The first line of the result is printed because of the fact that the 'animalPtr' of the 'Animal' type is effectively cast to the 'Dog' type and speak() function of the Dog class is conjured yet the casting of the 'Animal' type to 'Cat' type is unsuccessful because of the fact that 'animalPtr' focuses to a 'Dog' object subsequently, the dynamic cast fails because the typecasting is not safe.
3.Const cast operator:
The const cast operator is utilized to change the const or unstable (volatile) qualifier of a variable. It permits programmers to eliminate the constancy of an object temporarily and make alterations briefly. Caution should be practiced while utilizing const cast, as changing a const object can prompt to undefined way of behavior.
Syntax:
Const_cast <new_data_type> (input_value);
- Here, ‘new_datatype’ is the required data type which we need to convert and the ‘input_value’ is the value (or) expression we need to convert.
Example:
Program
#include <iostream>
using namespace std;
int main()
{
const int num = 5;
const int* ptr = #
int* nonConstPtr = const_cast<int*>(ptr);
*nonConstPtr = 10;
cout << "New number is: " << *nonConstPtr;
return 0;
}
Output:
4. Reinterpret cast operator:
The reinterpret cast operator is utilized to switch the pointer over completely to some other sort of pointer. It plays out no check regardless of whether the pointer changed type is of a similar kind.
Syntax:
Reinterpret_cast <new_datatype> (input_value);
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
int num = 152;
int* numPointer = #
char* characterPointer = reinterpret_cast<char*>(numPointer);
cout << "Integer Address: " << numPointer << endl;
cout << "Character Address: " << reinterpret_cast<void*>(characterPointer) << endl;
return 0;
}
Output:
Common char functions in C++:
In C++, character functions are operations that work with individual characters. These functions are important for the <cctype> and <cstdio> headers. Some of the regularly utilized character functions are:
isalpha(): Checks in the event that the input character is an alphabetic character (A-Z or a-z). Returns a non-zero value in the event that c is an alphabetic character and 0 in any other case.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch = 'K';
if(isalpha(ch))
{
std::cout << ch << " is an alphabetic character." << std::endl;
}
}
Output:
isdigit(): Checks in the event that the input character is a digit (0-9). Returns a non-zero value in the event that character is a digit and 0 in any other case.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch = '9' ;
if (isdigit(ch)) {
std::cout << ch << " is a digit." << std::endl;
}
}
Output:
isdigit(): Checks in the event that the input character is alphanumeric (either an alphabetic character or a digit). Returns a non-zero value in the event that character is alphanumeric, and 0 in any other case.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch = '/';
if (isalnum(ch))
{
std::cout << ch << " is alphanumeric." << std::endl;
}
else
{
std::cout << ch << " is not an alphanumeric." << std::endl;
}
}
Output:
isspace(): Checks in the event that the input character is a whitespace character (space, tab, newline, and so on). Returns a non-zero value in the event that character is a whitespace character and 0 in any other case.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch = ' ';
if (isspace(ch)) {
std::cout << ch << " is a space character." << std::endl;
}
else
{
std::cout << ch << " is not a space character." << std::endl;
}
}
Output:
toupper(): Switches a lowercase character over completely to its relating capitalized character. Returns the capitalized character.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch = 'j';
char upper = toupper(ch);
std::cout << ch << " converted to uppercase is: " << upper << std::endl;
}
Output:
tolower(): Switches an uppercase character over completely to its related loewrcase character. Returns the smaller character.
Example:
Program:
#include <iostream>
using namespace std;
int main()
{
char ch = 'L';
char lower = tolower(ch);
std::cout << ch << " converted to lowercase is: " << lower << std::endl;
}
Output:
Conclusion:
In C++, characters assumed as an essential part in dealing with text based data. They are addressed as single characters encased in single quotes (' ') and are put away as numerical values in the PC's memory. The ASCII encoding plan is normally used to map characters to their related numeric values. C++ gives a rich arrangement of operators and functions for working with characters. These incorporate essential activities like arithmetic operations, logical operations, and bitwise operations. Also, it will perform string isalpha(), isdigit(), isalphanumeric() etc. C++ also type casting between the characters, which includes explicit and implicit conversions.practicеs arе followеd, call by rеfеrеncе can bе usеd еfficiеntly in C++ codes.