////////////////////////////////////////////////// // cstring.cpp - how do I use C style strings? // ////////////////////////////////////////////////// #include #include using namespace std; // C language strings are arrays of chars // always ending with a null char, e.g. '\0' void main() { char *s1 = "this is the first string"; cout << "\n s1 = \"" << s1 << "\", its length is " << strlen(s1) << '\n'; cout << " the third char is " << s1[2] << '\n'; char s2[] = { 'a', 'e', 'i', 'o', 'u', '\0' }; cout << "\n s2 = \"" << s2 << "\", its length is " << strlen(s2) << '\n'; cout << " the fourth char is " << s2[3] << '\n'; char *s3 = new char[strlen(s1)+1]; if(!s3) throw "\n memory allocation failure\n\n"; strcpy(s3,s1); cout << "\n s3 is a copy of s1, e.g., \"" << s3 << "\"\n\n"; }