Arrays 05 - Intro To Char Array
Arrays 05 - Intro To Char Array
Lecture 7-Arrays
Introduction to Char Arrays
• Character arrays are of special interest, and you process them differently than you process other arrays.
• The C-style character string originated within the C language and continues to be supported within C++.
This string is actually a one-dimensional array of characters which is terminated by a null character '\0'.
Thus a null-terminated string contains the characters that comprise the string followed by a null.
• The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one more
than the number of characters in the word "Hello."
• Character arrays provide us the ability to store more than one character at a time.
char arr[10]={‘A’, ‘B’, ‘C’ , ‘D’, ‘E’};
• With character arrays, a loop doesn’t have to be used while taking the input. Just using
the statement cin>>arr; is enough to store an input. The array keeps taking input as long
as space isn’t pressed. As soon as space is pressed, the input terminates.
• In order to display a character array, all we need to do is to use the statement cout<<arr;
Example Codes for Array Declarations and
Array Printing
Output Output
Array as a String of Characters
• The most common use for one-dimensional arrays is to store strings of
characters. In C++, a string is defined as a character array terminated by
a null symbol \0.
• To declare an array arr that could hold a 10-character string, one would
write:
char str[11];
• Specifying the size as 11 makes room for the null at the end of the string
‘\0’ .
Sample Program
Output
Reading a char Array as string of characters
• Make a char array, that will receive the string, the target of a cin stream. The following program reads (part of)
a string entered by the user:
#include
int main()
{
char arr[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
cout << str;
return 0;
}
Problem: Entering the string “This is a test”, the above program only returns “This”, not the entire sentence.
Reason: The C++ input/output system stops reading a string when the first whitespace character is encountered.
Searching in char Arrays
Output