Sunteți pe pagina 1din 13

Declaring and Initializing an Array of Characters

When studying arrays, we were listing the numeric members of the array between curly bracket.
Here is an example:

int Number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Because a character is initialized by including it in single-quotes, when creating an array of


characters, to initialize it, you must also include each letter accordingly. A name such as James
can be initialized as follows:

char Name[6] = { 'J', 'a', 'm', 'e', 's' };

As done with other arrays, each member of this array of characters can be accessed using its
index. Here is an example:

#include <iostream>

using namespace std;

int main()

char Name[6] = { 'J', 'a', 'm', 'e', 's' };

cout << "The name is " << Name[0] << Name[1] << Name[2]

<< Name[3] << Name[4];

return 0;

The C/C++ provides another alternative. It allows you to declare and initialize the array as a
whole. To do this, include the name in double-quotes. With this technique, the curly brackets that
delimit an array are not necessary anymore. Here is an example:

char Name[12] = "James";

With this technique, the item between the double-quotes is called a string. It is also referred to
as the value of the string or the value of the variable.

When declaring and initializing an array of characters, the compiler does not need to know the
number of characters of the string. In fact, you can let the compiler figure it out. Therefore, you
can leave the square brackets empty:

char Name[] = "James";


After declaring such an array, the compiler would count the number of characters of the variable,
add one more variable to it and allocate enough space for the variable. The character added is
called the null-terminated character and it is represented as \0. Therefore, a string such as James
would be stored as follows:

J a m e s \0

This something you will need to remember regularly.

Color = Black

Country = Swaziland

Streaming an Array of Characters

Like any other variable, before using a string, you must first declare it, which is done by type the
char keyword, followed by the name of the variable, followed by square brackets. When declaring
the variable, if/since you do not know the number of characters needed for the string, you must
still provide an estimate number. You can provide a value large enough to accommodate the
maximum number of characters that would be necessary for the variable. For a person's name,
this could be 20. For the title of a book or a web page, this could be longer. Here are examples:

char Name[20];

char BookTitle[40];

char WebReference[80];

char WeekDay[4];

To request the value of an array of characters, use the cin extractor just like you would proceed
with any other variable, without the square bracket. Here is an example:

char WeekDay[12];

cout << "Enter today's name: ";

cin >> WeekDay;

To display the value of an array of characters, use the cout extractor as we have used it with all
other variables, without the square brackets. Here is an example:

#include <iostream>

using namespace std;

int main()

{
char WeekDay[12];

char EndMe[] = "\n";

cout << "Enter today's name: ";

cin >> WeekDay;

cout << "Today is " << WeekDay;

cout << EndMe;

return 0;

Here is an example of running the program:

Enter today's name: Thursday

Today is Thursday

Multidimensional Arrays of Characters

C/C++ treats arrays of characters differently than it does the other arrays. For example, we have
learned to declare a two-dimensional array of integers as follows:

int Number[2][6] = { { 31, 28, 31, 30, 31, 30 },

{ 31, 31, 30, 31, 30, 31 } };

This variable is in fact two arrays and each array contains 6 integers. For a string, if you want to
declare a two-dimension array of characters, the first dimension specifies the number of string in
the variable. The second dimension specifies the number of characters that each string can hold.
Here is an example:

char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

In this case, the StudentName variable is an array of 4 strings and each string can have a
maximum of 9 characters (+1 for the null-terminated character). To locate a string on this
variable, type the name of the array followed by its index, which is the index of the column. This
means that the first string of the StudentName array can be accessed with StudentName[0]. The
second would be StudentName[1], etc. This allows you to display each string on
the cout extractor:
#include <iostream>

using namespace std;

int main()

char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

cout << "Student Names";

cout << "\nStudent 1: " << StudentName[0];

cout << "\nStudent 2: " << StudentName[1];

cout << "\nStudent 3: " << StudentName[2];

cout << "\nStudent 4: " << StudentName[3];

return 0;

This would produce:

Student Names

Student 1: Hermine

Student 2: Paul

Student 3: Gertrude

Student 4: Leon

When declaring and initializing such an array, the compiler does not need to know the number of
strings in the array; it can figure it out on its own. Therefore, you can leave the first pair square
brackets empty. If you are only declaring the array but cannot initialize, then you must specify
both dimensions.

To request the values of the array, once again, locate each member using its index. Here is an
example:

Enther the first name of each player

Student 1: Walter

Student 2: Guy
Student 3: Celestin

Student 4: Maurand

Student 5: Phillipe

Student Names

Student 1: Walter

Student 2: Guy

Student 3: Celestin

Student 4: Maurand

Student 5: Phillipe

There are two alternatives to solve this problem: you can use the getline() function from
thebasic_string library or you can use the gets() function from the C language.

Pointers and Arrays of Characters

Declaring a Pointer to Characters

Earlier, we declared an array as follows:

char EndMe[] = "";

The name of the variable is a pointer to the beginning of the array. For this reason, the name of
the reason is sufficient to locate its value. Since in this case we do not specify the number of
characters in the array, we can also just use a pointer to the array as the beginning of the array.
The array can therefore be declared as follows:

char *EndMe = "";

Once again, to display the value of such an array, simply call its name on the cout extractor:

#include <iostream>

using namespace std;

int main()

char *EndMe = "";


cout << EndMe;

return 0;

To request the value of an array of characters from the user, you can declare a pointer to char
and initialize it with an estimate number of characters using the new operator. Here is an
example:

#include <iostream>

using namespace std;

int main()

char *StudentName = new char[20];

cout << "Enter Sudent First Name: ";

cin >> StudentName;

cout << "\nStudent First Name: " << StudentName;

return 0;

Here is an example of running the program:

Enter Sudent First Name: Charlotte

Student First Name: Charlotte

Declaring and Initializing an Array of Characters


From our study and use of characters, we have seen that, to declare a character variable, we
can use any C++ valid name. To initialize a character variable, type it between single-quotes.
Here is an example:

char Answer = y;

To declare an array of characters, type the char keyword followed by the techniques we used to
declare the other arrays. The syntax is:

char ArrayName[Dimension];

The char keyword lets the compiler know that you are declaring a variable of character type.
The square brackets let the compiler know that you are declaring an array. The name of the
array follows the same rules and suggestions we have used for the other variables. Once again,
the dimension of the array could be an approximation of the number of characters you anticipate.

To initialize an array of characters, you use the curly brackets. Each character must be enclosed
in single-quotes. If you know the characters you will be using to initialize the array, you should
omit specifying the dimension. Here is an example:

char Color[] = { 'B', 'l', 'a', 'c', 'k' };

Another technique used to initialize an array of characters is to type the group of characters
between double-quotes. Since you know the array, let the compiler figure out its dimension.
Here is an example:

char Country[] = "Swaziland";

Any of these two techniques would allow you to display the string using the cout operator. The
compiler already knows the dimension and the contents of the array:

#include <iostream>

using namespace std;

int main()

char Color[] = { 'B', 'l', 'a', 'c', 'k' };

char Country[] = "Swaziland";

cout << "Color = " << Color << endl;

cout << "Country = " << Country;

return 0;

}
This would produce:

Color = Black

Country = Swaziland
Requesting an Array of Characters

Instead of initializing an array, sometimes you will have to wait until the program is running, to
assign a value to the array. First, you must declare the array, specifying an approximate
dimension. To request the value of an array of characters, use the cin operator, specifying only
the name of the array. Here is an example:

#include <iostream>

using namespace std;

int main()

char FirstName[20];

char MI;

char LastName[20];

cout << "The following pieces of information are need"

<< "to complete your application\n";

cout << "First Name: ";

cin >> FirstName;

cout << "Middle Initial: ";

cin >> MI;

cout << "Last Name: ";

cin >> LastName;

cout << "\nMember Information";

cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName;

return 0;
}

Here is an example of running the program:

The following pieces of information are need

to complete your application

First Name: Michael

Middle Initial: J

Last Name: Callhoun

Member Information

Full Name: Michael J. Callhoun

If you use the normal cin operator above, the compiler expects the user to type a one-word
string from the keyboard. If you want the user to type text that includes space, you should use
the cin::getline() function. The syntax of the getline() function is:

cin.getline(ArrayName, Dimension, Delimiter=\n);

The array name is the one you used when declaring the array. The dimension is the same value
you set when declaring the variable. The delimiter is an optional character that the user would
type to specify the end of the string. By default, the compiler expects the user to press Enter to
end the string. Logically, the following program illustrates the use of the cin::getline() function
to request text strings from the user:

#include <iostream>

using namespace std;

int main()

char Author[40];

char Title[40];

char Publisher[50];

cout << "Book Collection\n";

cout << "Author: ";

cin.getline(Author, 40);
cout << "Title: ";

cin.getline(Title, 40);

cout << "Publisher: ";

cin.getline(Publisher, 50);

cout << "\nBook Information";

cout << "\nAuthor Name: " << Author

<< "\nBook Title: " << Title

<< "\nPublisher: " << Publisher;

return 0;

Here is an example of running the program:

Book Collection

Author: Elliot Mendelson

Title: 3000 Solved Problems In Calculus

Publisher: McGraw Hill

Book Information

Author Name: Elliot Mendelson

Book Title: 3000 Solved Problems In Calculus

Publisher: McGraw Hill


Arrays of Characters and Pointers

Declaration of an Array of Characters

We have learned to declare an array of characters using the square brackets and to initialize it
using the assignment operator. By not specifying the dimension of the array, we are relying on
the compiler to find out how many items the array has. Here is an example:

#include <iostream>
using namespace std;

int main()

char Country[] = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n";

return 0;

As you can see for this example, to display the value of the Country variable, although it is an
array, all the compiler needs is the name. How come? As it happens, when you create an array
of characters, such as the Country variable above, the name of the array is the same as
Country[0]. In other words, it represents the beginning of the space memory occupied by the
variable. As we saw when studying pointers, this beginning of the space occupied by a variable
is referred to as its address. Because the compiler knows this and is able to figure it out, C++
provides another solution. Instead of declaring the array with empty square brackets, since we
are in fact referring to the address of the variable, we can declare it a pointer to char. Therefore,
the above program can be written as follows:

#include <iostream>

using namespace std;

int main()

char *Country = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n";

return 0;

Both programs would produce the same result. There is something important to know about this
new version. The asterisk on the name informs the compiler that it should consider the Country
variable starting at its address and up. If you do not initialize the variable, the compiler would
not complain as long it is now able to locate the variable. Based on this, you can initialize the
variable when you are ready and not necessarily when you declare it. Keep in mind that this
theory is valid only for an array of characters; for example the following program will not
compile:

#include <iostream>

using namespace std;

int main()

double *Value;

Value = 12.55;

cout << "Value = " << Value;

return 0;

On the other hand, the following declaring of an array of characters and its later initialization is
perfectly legal:

#include <iostream>

using namespace std;

int main()

char *Country;

Country = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n";

return 0;

}
Dynamic Arrays of Characters
A dynamic object is one whose memory is requested and used only when needed. Such objects
are created using the new operator. In the same way, to dynamically create an array, you use
the new operator. To do this, the variable must be declared a pointer to char, as done above.
Then assign the new char expression that followed by a pair of square brackets. In the square
brackets, specify the desired dimension of the array. An example would be:

char *Country = new char[20];

After declaring such a variable, you can assign it any value you want. Here is an example:

#include <iostream>

using namespace std;

int main()

char *Country = new char[20];

Country = "Equatorial Guinea";

cout << "Country Name: " << Country;

cout << "\n\n";

return 0;

S-ar putea să vă placă și