C++: Using Char Array Strings

Using Char Array Strings

In this C++ video tutorial, we demonstrate how to use strings in the form of char arrays. Although the STL string type has superceded these types of strings, they have been and remain commonly used in practice.

The video presents methods of how input, copy, get the length of, concatenate, compare, and tokenize char array strings. Most of the functionality for operating on char array strings is contained in the <cstring> library and the entire sets of cstring functions is described in our C++ reference section, along with example programs. Instead of demonstrating more cstring functions here, we show some programs with common char array string functions, which are contained in <cstdlib>.

For our first code example, we will show how to convert a string into a numerical value, using the atof() function in cstdlib:

#include <iostream>
#include <cstdlib>

int main() {
    using namespace std;

    char caPI[] = "3.14159";
    // Convert the string to a double
    double dPI  = atof(caPI);
    cout << "Converts to a double value as " << dPI << endl;

    return 0;
}

The code above takes the string approximation of Pi and converts it to a double using the function atof(), which stands for ASCII to floating point. The output of the code above looks like this:




Below, we present code to sort a list of movie names, using the qsort() function. We also use the strcmp() function from cstring. However, we need to wrap that comparison function in order to create a function with the proper signature. Also, the value 20*sizeof(char) is the size of the char arrays containing each title. This is necessary because the quick sort algorithm in qsort() performs a memory swap on these arrays.

// Sort a list of string and then binary search on it.
#include <iostream>
#include <cstdlib>
#define MMovieCount 5

int Compare(const void* vpStr1, const void* vpStr2) {
    return strcmp((const char*)vpStr1, (const char*)vpStr2);
}

int main() {
    using namespace std;

    char caaMovies[MMovieCount][20] = {
        "The Matrix",
        "Demolition Man",
        "The Terminator",
        "Back to the Future",
        "Star Wars"};

    // Sort the list of movies with qsort()
    qsort(caaMovies, MMovieCount, 20*sizeof(char), Compare);
    for (int i = 0; i < MMovieCount; ++i) {
        cout << caaMovies[i] << endl;
    }

    // Find a movie using the bsearch()
    char* cpResult =  (char*)bsearch("Back to the Future",
        caaMovies, MMovieCount, 20*sizeof(char), Compare);
    cout << "Found: " << cpResult << endl;

    return 0;
}

Below, the output shows the movies in alphabetically sorted order:

  1. Back to the Future
  2. Demolition Man
  3. Star Wars
  4. The Matrix
  5. The Terminator

Also, the binary search function found the movie, "Back to the Future."