CIS 67 : Using C Strings

C++ has grown out of C and most C programs remain legal in C++. One of the legacies of C that you are likely to encounter in C++ are C strings. For example, if you have:
	cout << "Enter file name : ";
	string filename;
	cin >> filename;
	ifstream fin;
	fin.open(filename);
you will get an error. You need to say
	fin.open(filename.c_str());
i.e. open requires a C string.
A C string is a character array with as rightmost element '\0'. For example
	char flowers[] = "roses";
	cout << sizeof(flowers) << endl; 
outputs 6 and not 5 since a position is taken up for '\0'.
Notice that if instead we had written:
	char *plants = "pines";
	cout << sizeof(plants) << endl;
the output on my machine would have been 8 (and might have been 4 on other machines) because plants is a pointer (i.e. an address) to a character array, not the array itself.

C and C++ standard libraries give us a number of functions for using C strings. To use these functions you need to have the compiler directive
#include <cstring>

Among the Standard C functions for C strings you should remember at least strlen, strcmp, strcpy, strcat. Here are some examples using C strings: