C-Strings in C++

C-string is an array of characters that ends with the null terminator character ‘\0’. You can process C-strings using C-string functions in the C++ library.

A C-string is an array of characters ending with the null terminator (‘\0’), which indicates where a string terminates in memory. Recall that a character that begins with the backslash symbol (\) is an escape sequence in Section 4.3.3, “Escape Sequences for Special Characters.” The symbols \ and 0 (zero) together represent one character. This character is the first character in the ASCII table.

Every string literal is a C-string. You can declare an array initialized with a string literal. For example, the following statement creates an array for a C-string that contains characters ‘D’, ‘a’, ‘l’, ‘l’, ‘a’, ‘s’, and ‘\0’, as shown in Figure 7.9.

Note that the size of the array is 7 and the last character in the array is ‘\0’. There is a subtle difference between a C-string and an array of characters. For example, the following two statements are different:

char city1[] = “Dallas”; // C-string

char city2[] = {‘D’, ‘a’, ‘l’, ‘l’, ‘a’, ‘s’}; // Not a C-string

The first statement is a C-string and the second statement is just an array of characters. The former has 7 characters including the last null terminator and the latter has 6 characters.

1. Input and Output of C-Strings

To output a C-string is simple. Suppose s is an array for a C-string. To display it to the console, simply use

cout << s;

You can read a C-string from the keyboard just as you do a number. For example, consider the following code:

  1. char city[7];
  2. cout << “Enter a city: “;
  3. cin >> city; // Read to array city
  4. cout << “You entered ” << city << endl;

When you read a string to an array, be sure to leave room for the null terminator character. Since city has a size 7, your input should not exceed 6 characters.This approach to reading a string is simple, but there is a problem. The input ends with a whitespace character. You can­not read a string that contains a space. Suppose you want to enter New York; then you have to use an alternative approach. C++ provides the cin.getline function in the iostream header file, which reads a string into an array. The syntax of the function is as follows:

cin.getline(char array[], int size, char delimitChar)

The function stops reading characters when the delimiter character is encountered or when the size – 1 number of characters have been read. The last character in the array is reserved for the null terminator (                                                   ). If the delimiter is encountered, it is read but is not stored in the

array. The third argument delimitChar has a default value (‘\n’). The following code uses the cin.getline function to read a string:

  1. char city[30];
  2. cout << “Enter a city: “; // i.e., New York
  3. getline(city, 30, ‘\n’); // Read to array city
  4. cout << “You entered ” << city << endl;

Since the default value for the third argument in the cin.getline function is ‘\n’, line 3 can be replaced by

cin.getline(city, 30); // Read to array city

2. C-String Functions

Given that a C-string ends with a null terminator, C++ can utilize this fact to process C-strings efficiently. When you pass a C-string to a function, you don’t have to pass its length, because the length can be obtained by counting all characters from left to right in the array until the null terminator character is reached. Here is the function for obtaining the length of a C-string:

unsigned int strlen(char s[])

{

int i = 0;

for ( ; s[i] != ‘\0’; i++);

return i;

}

In fact, strlen and several other functions are provided in the C++ library for processing C-strings, as shown in Table 7.1.

3. Copying Strings Using strcpy and strncpy

Function strcpy can be used to copy a source string in the second argument to a target string in the first argument. The target string must have already been allocated sufficient memory for the function to work. A common mistake is to copy a C-string using code like this:

char city[30] = “Chicago”;

city = “New York”; // Copy New York to city. Wrong!

In order to copy “New York” to city, you have to use

strcpy(city, “New York”);

The strncpy function works like strcpy, except that it takes a third argument specifying the number of the characters to be copied. For example, the following code copies the first three characters “New” to city.

char city[ ];

strncpy(city, “New York”, 3);

There is a problem with this code. The strncpy function does not append a null terminator to the target string if the specified number of characters is less than or equal to the length of the source string. If the specified number of characters is greater than the length of the source string, the source string is copied to the target padded with null terminators all the way up to the end of the target string. Both strcpy and strncpy can potentially override the bounds of an array. To ensure safe copying, check bounds before using these functions.

4. Concatenating Strings Using strcat and strncat

Function strcat can be used to append the string in the second argument to the string in the first argument. For the function to work, the first string must have already been allocated suf­ficient memory. For example, the following code works fine to append s2 into s1.

char s1[7] = “abc”;

char s2[4] = “def”;

strcat(s1, s2);

cout << si << endl; // The printout is abcdef

However, the following code does not work, because there is no space to add s2 into s1.

char s1[4] = “abc”;

char s2[4] = “def”;

strcat(s1, s2);

The strncat function works like strcat, except that it takes a third argument specifying the number of the characters to be concatenated from the target string with the source string. For example, the following code concatenates the first three characters “ABC” to s:

char s[9] = “abc”;

strncat(s, “ABCDEF”, 3);

cout << s << endl; // The printout is abcABC

Both strcat and strncat can potentially override the bounds of an array. To ensure safe concatenating, check bounds before using these functions.

5. Comparing Strings Using strcmp

Function strcmp can be used to compare two strings. How do you compare two strings? You compare their corresponding characters according to their numeric codes. Most compilers use the ASCII code for characters.The function returns the value 0 if s1 is equal to s2, a value less than 0 if s1 is less than s2, and a value greater than 0 if s1 is greater than s2. For example, suppose s1 is “abc” and s2 is “abg”, and strcmp(s1, s2) returns a negative value. The first two characters (a vs. a) from s1 and s2 are compared. Because they are equal, the second two characters (b vs. b) are compared. Because they are also equal, the third two characters (c vs. g) are compared. Since the character c is 4 less than g, the comparison returns a negative value. Exactly what value is returned depends on the compiler. Visual C++ and GNU compil­ers return -1, but Borland C++ compiler returns -4 since the character c is 4 less than g.

Here is an example of using the strcmp function:

char s1[] = “Good morning”;

char s2[] = “Good afternoon”;

if (strcmp(s1, s2) > 0 )

cout << “s1 is greater than s2” << endl;

else if (strcmp(s1, s2) == 0)

cout << “s1 is equal to s2” << endl;

else

cout << “s1 is less than s2” << endl;

It displays s1 is greater than s2.

The strncmp function works like strcmp, except that it takes a third argument specifying the number of the characters to be compared. For example, the following code compares the first four characters in the two strings.

char s1[] = “Good morning”;

char s2[] = “Good afternoon”;

cout << strncmp(s1, s2, 4) << endl;

It displays 0.

6. Conversion between Strings and Numbers

Function atoi can be used to convert a C-string into an integer of the int type and function atol can be used to convert a C-string into an integer of the long type. For example, the following code converts numerical strings si and s2 to integers:

char s1[] = “65”;

char s2[] = “4”;

cout << atoi(s1) + atoi(s2) << endl;

It displays 69.

Function atof can be used to convert a C-string into a floating-point number. For exam­ple, the following code converts numerical strings s1 and s2 to floating-point numbers:

char s1[] = “65.5”;

char s2[] = “4.4”;

cout << atof(s1) + atof(s2) << endl;

It displays 69.9.

Function itoa can be used to convert an integer into a C-string based on a specified radix. For example, the following code

char s1[15];
char s2[15];
char s3[15];
itoa(
100, s1, 16);
itoa(
100, s2, 2);
itoa(
100, s3, 10);
cout <<
“The hex number for 100 is ” << s1 << endl;
cout <<
“The binary number for 100 is ” << s2 << endl;
cout <<
“s3 is ” << s3 << endl;

displays

The hex number for 100 is 64

The binary number for 100 is 1100100

s3 is 100

Note that some C++ compilers may not support the itoa function. 7.18 What are the differences between the following arrays?

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *