C-Style Strings
- C Strings
- Making C strings available in your programs
- There is nothing to include, C Strings (also known as character arrays) are a built-in part of the C++ language.
- Declaration Examples:
- char myString1[] = "This is a string"; // just big enough to hold the string value
- char myString2[80] = "This string has enough space for 80 characters";
- char myString3[40]; // this string has space for forty characters, but they are not initialized
- Conceptual View: While we think of a C++ string as having two parts (contents and length), a C string has only the contents, the length is implicitly defined by where the first NULL character (e.g., '\0') appears.
- Input
- Via an input stream
- By default "white space" terminates the input of a string
- Example
- Given the code:
char name[20];
cout << "What is your name: ";
cin >> name;
Suppose the user of the program types: "Joe Cool"
- The string name would get assigned the first name (i.e., "Joe") only, because the last name is separated from the first by a space.
- Via assignment
- C Strings cannot be assigned as other fundamental objects
- Example: Assuming name is decalred as above, the following assignment is illegal
- C Strings are assigned and compared using pre-defined functions
- Assignment: strcpy(name, "Skippy"); // accomplishes the assignment above
- Comparison: strcmp(name, "Spunky"); // used in place of name == "Spunky"
- Examples
- Examples of various C string pre-defined functions: cstring.cpp