One Dimensional Array part4 (Array Of Character)

Estimated reading: 8 minutes 111 Views

An array of characters in C++ is often referred to as a “string.” It is a fundamental data structure used to store sequences of characters, such as words, sentences, or even individual characters. In C++, strings are represented as arrays of characters, terminated by a special null character, ‘\0’, which indicates the end of the string.

to initiate a character we use a single quotation like this ‘L’.

Example 1:

char ch[5] = { 'a','b','c','d','e','\0' };

The null character (‘\0’), NULL or 0, is used to indicate the end of the string. This character is automatically added to the end of string literals and is crucial for various string manipulation functions.

If you add characters after the null character they won’t be read by the program.

Example 2:

#include <iostream>
using namespace std;
int main()
{
    char ch[5];
    cin >> ch;
    cout << ch << endl;
    return 0;
}

This code reads a sequence of characters into a char array and then prints the array. However, there are a few things to note about potential issues and improvements in the code:

  1. Array Size:
    The char array ch has a size of 5. If you enter more than 4 characters, it will result in a buffer overflow, causing undefined behavior. It’s essential to ensure that the input doesn’t exceed the array size.
  2. Input Method:
    When using cin >> ch, it reads characters until it encounters whitespace. If you want to read an entire line (including spaces), you should use cin.getline(ch, size) or cin.get(ch, size).

Example 3:

#include <iostream>
using namespace std;

int main() {
    char ch[10];

    // Read up to 9 characters into the char array
    cin.get(ch, 10);

    // Output the char array
    cout << ch << endl;

    return 0;
}

This code reads up to 9 characters (plus the null terminator) into a char array using cin.get() and then prints the array.
Here are a few points to note:

  1. Array Size:
    The char array ch has a size of 10. Since cin.get() reads up to one less than the specified size (leaving space for the null terminator), it effectively reads up to 9 characters.
  2. Input Method:
    cin.get(ch, 10) reads characters until either 9 characters are read, the newline character is encountered, or the end of file is reached. It stops reading after reaching the specified number of characters or encountering one of these conditions.
  3. Null Terminator:
    The array is not explicitly null-terminated by cin.get(); however, C++ streams automatically append a null terminator at the end of the string when reading into a character array. Therefore, the array ch is effectively treated as a C-style string.

Output:

The cout << ch << endl; statement prints the contents of the char array, treating it as a null-terminated string. If fewer than 9 characters were entered, it prints the characters entered. If 9 characters were entered, it prints those 9 characters followed by the null terminator.

Input Limitation:

Keep in mind that the user input is limited to 9 characters, and exceeding this limit may lead to unexpected behavior. It’s essential to handle potential input overflows based on the specific requirements of your program.

Example 4:

#include <iostream>
using namespace std;
int main()
{
    char ch1[10], ch2[10];
    cin.getline(ch1, 10);
    cin.getline(ch2, 10);
    cout << ch1 << endl;
    cout << ch2 << endl;
    return 0;
}

This code reads two lines of input into separate char arrays and then prints each array on a new line.

Here are some points to note:

  1. Array Size:
    Both ch1 and ch2 are char arrays with a size of 10. The cin.getline() function reads characters until it encounters a newline character or reaches the specified size (leaving space for the null terminator).
  2. Input Limitation:
    The user input for each line is limited to 9 characters, and the null terminator is automatically added by cin.getline().
  3. Handling Spaces:
    Unlike cin >>, cin.getline() reads the entire line, including spaces. This allows you to input strings with spaces.

Output:

The cout << ch1 << endl; statement prints the contents of the first char array, treating it as a null-terminated string.
Similarly, cout << ch2 << endl; prints the contents of the second char array.
Newline Character:

Each call to cin.getline() reads until it encounters a newline character or reaches the specified size. The newline character is consumed but not stored in the arrays.
This code allows you to input two lines of text (up to 9 characters each) and then prints each line on a new line. It’s suitable for reading and displaying multiple lines of text, handling spaces, and avoiding buffer overflow issues.

 

There are some functions that are part of the C Standard Library and are used for manipulating C-style strings, which are arrays of characters. Here’s an explanation of each function:

  • strcpy (String Copy):

Description: The strcpy function is used to copy the contents of one C-style string to another.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch1[] = "AAA";
    char ch2[4];
    strcpy_s(ch2, ch1);
    cout << ch2 << endl;
    return 0;
}
  1. strcpy_s Function:
    The strcpy_s function is part of the C Standard Library and is designed to provide safer string copying by including a size check.
  2. Buffer Size:
    The size of ch2 is explicitly specified as 4, which includes three characters for the content of ch1 (“AAA”) and one additional space for the null terminator (‘\0’).
  3. Safe String Copy:
    Unlike the standard strcpy function, strcpy_s requires you to provide the size of the destination array (destsz). It checks if there is enough space in the destination array to accommodate the source string and the null terminator. If there isn’t enough space, the function does not perform the copy and returns an error code.

Output:

The cout << ch2 << endl; statement outputs the contents of ch2, which should be “AAA” in this case.

By using strcpy_s, you are taking steps to prevent buffer overflow issues that could occur if the destination array is not large enough to hold the contents of the source string. This is a good practice for enhancing the safety and robustness of your code.

  • strcat (String Concatenate):

Description: The strcat function is used to concatenate (append) the contents of one C-style string to another.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch1[] = "AAA";
    char ch2[4] = "HH";
    strcat(ch2, ch1);
    cout << ch2 << endl;
    return 0;
}
  1. strcat Function:
    The strcat function is part of the C Standard Library and is used to concatenate the contents of one C-style string to another.
  2. Buffer Size:
    The size of ch2 is explicitly specified as 4, which includes two characters (“HH”) and one additional space for the null terminator (‘\0’).
  3. Concatenation:
    The strcat(ch2, ch1); line appends the contents of ch1 to the end of ch2. It starts copying characters from the null terminator of ch2 to the end of ch1 until it encounters the null terminator of ch1. The null terminator of ch2 is updated accordingly.

Output:

The cout << ch2 << endl; statement outputs the contents of ch2 after the concatenation. Since the size of ch2 is limited to 4, it can hold “HH” and the null terminator, but only one additional character from ch1 (“A”) can be accommodated.
Result:

The output of this code is “HHA”, which is the result of concatenating “AAA” to the end of the existing content in ch2.
It’s important to ensure that the destination array has enough space to accommodate the concatenated string, and using functions like strcat requires careful management of buffer sizes to prevent buffer overflows.

  • strcmp (String Compare):

Description: The strcmp function is used to compare two C-style strings lexicographically.

The strcmp function returns an integer value indicating the lexicographic relationship between the two strings. It returns:
– 0 if the strings are equal,
– a negative value if str1 is lexicographically less than str2,
– a positive value if str1 is lexicographically greater than str2.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    cout << strcmp("abc", "abc") << endl;
    return 0;
}

Output:

The cout statement outputs the result of the comparison using strcmp. In this case, since the strings are equal, the output will be 0.

The strcmp function is commonly used for sorting strings, dictionary operations, and other scenarios where you need to determine the lexicographic order of strings. It’s important to handle the result appropriately based on your specific requirements in the program.

  • strlen (String Length):

Description: The strlen function is used to determine the length of a C-style string.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch[] = "jjjjjjjjjjjjjjjjjjjjj";
    cout << strlen(ch) << endl;
    return 0;
}

Output:

The cout statement outputs the result of strlen(ch), which is the length of the string “jjjjjjjjjjjjjjjjjjjjj”. Since there are 21 characters in the string, the output will be 21.

The strlen function is useful for obtaining the length of strings, and it’s important to note that the length does not include the null terminator. Make sure that the string is properly null-terminated to get accurate results with strlen.

 

 

 

 

 

Share this

One Dimensional Array part4 (Array Of Character)

Or copy link

CONTENTS
English