C++ Char Data Type with Examples

What is Char?

Char is a C++ data type designed for the storage of letters. Char is an abbreviation for an alphanumeric character. It is an integral data type, meaning the value is stored as an integer. A char takes a memory size of 1 byte. It also stores a single character.

What is ASCII?

The char value is interpreted as an ASCII character. This is similar to how Boolean values are interpreted as being true or false. ASCII is an acronym for American Standard Code for Information Interchange. It defines a specific way of representing English characters as numbers.

The numbers range between 0 and 127. For example, the character ‘a’ is equivalent to ASCII code 97.

Char Declaration

To declare a char variable in C++, we use the char keyword. This should be followed by the name of the variable. The variable can be initialized at the time of the declaration. The value of the variable should be enclosed within single quotes.

Syntax

Here is the syntax for char declaration in C++:

char variable-name;

The variable-name is the name to be assigned to the variable.

If a value is to be assigned at the time of declaration, you can use this syntax:

char variable-name = 'value';	
  • The variable-name is the name of the char variable.
  • The value is the value to be assigned to the char variable.

Example 1:

#include <iostream>
using namespace std;
int main() {
	char grade = 'B';
	cout << "I scored a: "<<grade;
	return 0;
}

Output:

Char Declaration

Here is a screenshot of the code:

Char Declaration

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Including the std namespace in our code in order to use its classes without calling it.
  3. Calling the main() function. The program logic should be added within the body of this function.
  4. Declare a character variable named grade. The variable has also been assigned a value of B. Notice the value of the variable is enclosed within single quotes.
  5. Print the value of the variable grade alongside other text on the console.
  6. The program must return value upon successful completion.
  7. End of the body of the main() function.

Printing ASCII Value

As stated above, each character is interpreted as ASCII character. It’s possible for you to get the ASCII value of any character. You simply pass the character to the int() function. This process is called type casting. Let’s demonstrate this:

Example 2:

#include <iostream>
using namespace std;
int main() {
	char ch;
	cout << "Enter any character: ";
	cin >> ch;
	cout << "The ASCII Value of " << ch << " is " << int(ch);
	return 0;
}

Output:

Printing ASCII Value

Here is a screenshot of the code:

Printing ASCII Value

Code Explanation:

  1. Including the iostream header file into our code in order to use its functions.
  2. Including the std namespace into our code in order to use its classes without calling it.
  3. Calling the main() function. The program logic should be added within the body of this function.
  4. Declare a char variable named ch.
  5. Print some text on the console. The text asks the user to enter a value for the variable ch.
  6. Read the user input from the keyboard and store it in the variable ch.
  7. Print some text on the console. The text will include the character you entered for variable ch, the ASCII value of this character, and other text.
  8. The program must return value upon successful completion.
  9. End of the body of the main() function.

Printing Char Value

Given an ASCII value, the C++ compiler can return the corresponding character. You declare a char variable and assign it an integer value. It will be converted to the corresponding character value.

Example 3:

#include <iostream>
using namespace std;
int main() {
	char x = 64, y = 66, z = 71;
	cout << x;
	cout << y;
	cout << z;
	return 0;
}

Output:

Printing Char Value

Here is a screenshot of the code:

Printing Char Value

Code Explanation:

  1. Including the iostream header file into the code. We will then use its functions without getting errors.
  2. Include the std namespace into the code. We will use its classes without calling it.
  3. Calling the main() function. The program logic should go into the body of this function.
  4. Declare three char variables x, y, and z. The three have been assigned integer values of 65, 66, and 67. These will be treated as ASCII values for characters.
  5. Print out the value of variable x on the console. Since x was declared as a char, the char with ASCII value of 65 will be returned, that is, A.
  6. Print out the value of variable y on the console. Since y was declared as a char, the char with ASCII value of 66 will be returned, that is, B.
  7. Print out the value of variable z on the console. Since z was declared as a char, the char with ASCII value of 67 will be returned, that is, C.
  8. The program must return value upon successful completion.
  9. The end of the body of the main() function.

Inputting Chars

We can use the std::cin function to read a char entered by the user via the keyboard. The std::cin will allow you to enter many characters. However, the character variable can hold only one character. This means only the first character entered will be extracted and stored in the character variable. The rest will remain in the buffer used by std::cin. To extract it, make subsequent calls to the std::cin.

Example 4:

#include <iostream>
using namespace std;
int main() {
	cout << "Type a sequence of characters: "; 
	char ch;
	cin >> ch; 
	cout <<"The ASCII code of "<< ch << " is "<< int(ch) << '\n';
	cin >> ch; 
	cout <<"The ASCII code of " << ch << " is "<< int(ch) << '\n';
	return 0;
}

Output:

Inputting Chars

Here is a screenshot of the code:

Inputting Chars

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Calling the main() function. The program logic should be added within the body of this function.
  4. Print some text on the console.
  5. Declare a character variable named ch.
  6. Read user input from the keyboard. The input will be stored in the variable ch. Since a user will type a character sequence like abc, only the first character, a, will be stored in variable ch.
  7. Printing the first character entered, its ASCII code and other text on the console. The ASCII code is determined by passing the character variable to the int() function.
  8. Read the next character that was entered by the user. The user won’t be required to enter a new character. It will instead read the second character that was entered, that is, b.
  9. Printing the second character entered, its ASCII code and other text on the console. The ASCII code is determined by passing the character variable to the int() function.
  10. The program must return value upon successful completion.
  11. End of the body of the main() function.

Converting Character to String

There exist a number of ways that we can use to convert characters to strings.

Let’s discuss them:

#1: Using Constructor given by a String Class

This can be done using the following syntax:

string st(int n,char x);

The parameter n denotes the size of the string that is to be generated.

The parameter x is the character to convert to a string.

The function returns a string.

Example 5:

#include<iostream>
#include <string>
using namespace std;
int main() {
	string st(1, 'C');
	cout << "The resulting string is : " << st;
	return 0;
}

Output:

Converting Character to String

Here is a screenshot of the code:

Converting Character to String

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Calling the main() function. The program logic should be added within the body of this function.
  5. Convert the character “C” into a 1-length string and assign the resulting string to the variable st.
  6. Print the value of the string st on the console alongside other text.
  7. The program must return value upon successful completion.
  8. End of the body of the main() function.

#2) Using the std::string Operators = and +=

The = and += operators are already overloaded with characters. The two can be used to convert a particular character to a string.

Example 6:

#include<iostream>
#include <string>
using namespace std;
int main() {
	string st;
	char b = 'B';
	st = 'A';
	st += b;
	cout << "The resulting string is : " << st;
	return 0;
}

Output:

Converting Character to String

Here is a screenshot of the code:

Converting Character to String

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Calling the main() function. The program logic should be added within the body of this function.
  5. Create a string variable named st.
  6. Create a character named b with a value of B.
  7. Assign a value of A to the string named st.
  8. Use the += operator to convert characters into a string.
  9. Print the value of the string st on the console alongside other text.
  10. The program must return value upon successful completion.
  11. End of the body of the main() function.

#3: Using std::string Methods

The std::string class comes with many overloaded functions that can help you convert characters into strings.

They include:

  • push_back This function assigns a particular character to a string’s end. It is overloaded for characters.It takes the following syntax:
    void push_back(char ch)
    

    The parameter ch is the character that is to be changed to a string.

  • append It assigns many copies of a particular character to a string.The function takes the following syntax:
    string& append(size_t n,char ch)
    

    The parameter n denotes the times that the character will be appended.

    The parameter ch is the character to append to string.

  • assign This function replaces the current contents of the string with n copies of the specified character.It takes the following syntax:
    string& assign(size_t n,char ch);

    The parameter n denotes the total copies for the character.

    The parameter ch is the character to copy into the string.

  • insert The insert function inserts n copies of a character at the starting position of the string, as specified in the arguments. It takes the following syntax:
    string& insert(size_t p,size_t n,char ch);

    The p parameter denotes the position from the start where characters will be inserted.

    The parameter n denotes the total copies for the character.

    The parameter ch is the character to be insert in the string.

Example 7:

#include<iostream>
#include <string>
using namespace std;
int main() {
	string st;
	st.push_back('A');
	cout << "push_back A returns : " << st << endl;
	st = "";
	st.append(1, 'C');
	cout << "append C returns : " << st << endl;
	st = "";
	st.assign(1, 'D');
	cout << "assign D returns : " << st << endl;
	st.insert(0, 1, 'E');
	cout << "insert single character returns : " << st << endl;
	return 0;
}

Output:

Converting Character to String

Here is a screenshot of the code:

Converting Character to String

  1. Include the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Calling the main() function. The program logic should be added within the body of this function.
  5. Create a string variable named st.
  6. Assign the character A to the end of the string.
  7. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  8. Set the value of the string st to empty.
  9. Assign single character C to the string named st.
  10. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  11. Set the value of the string st to empty.
  12. Replace contents for string st with single character D.
  13. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  14. Insert single character E to the string named st from its first index.
  15. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  16. The program must return value upon successful completion.
  17. End of the body of the main() function.

#4: Using std::stringstream

To use this class to convert character to a string, insert the character into stream.

They’ll be written to the string.

Example 8:

#include<iostream>
#include <string>
#include <sstream>

using namespace std;
int main() {

	string st;

	stringstream myst;

	myst << 'A'; 
	myst >> st;

	cout << "The conversion of the single character returns the string: " << st;

	return 0;
}

Output:

Converting Character to String

Here is a screenshot of the code:

Converting Character to String

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the sstream header file in our code to use its functions.
  4. Include the std namespace in our code to use its classes without calling it.
  5. Calling the main() function. The program logic should be added within the body of this function.
  6. Create a string variable named st.
  7. Create a stream variable named myst.
  8. Insert the character A into stream object named myst.
  9. Convert the stream object into a string.
  10. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  11. The program must return value upon successful completion.
  12. End of the body of the main() function.

Summary

  • A char is a C++ data type used for the storage of letters.
  • C++ Char is an integral data type, meaning the value is stored as an integer.
  • It occupies a memory size of 1 byte.
  • C++ Char only stores single character.
  • Char values are interpreted as ASCII characters.
  • ASCII is an acronym for American Standard Code for Information Interchange.
  • It states a specific way of representing English characters in the form of numbers.
  • To see the ASCII value of a character, we pass it to the int() function.
  • To see the corresponding char value of ASCII value, we define the ASCII as a character.