Download C-Strings (Character Arrays) and more Schemes and Mind Maps Design in PDF only on Docsity!
C++ Programming: Program DesignIncluding Data Structures, Fourth
C-Strings (Character Arrays)
- Character array: an array whose components are of type char
- C-strings are null-terminated ('\0') character arrays
- Example:
- 'A' is the character A
- "A" is the C-string A
- "A" represents two characters, 'A' and '\0‘
C++ Programming: Program DesignIncluding Data Structures, Fourth
C-Strings (Character Arrays)
(continued)
- Consider the statement char name[16];
- Since C-strings are null terminated and name has 16 components, the largest string that it can store has 15 characters
- If you store a string of length, say 10 in name
- The first 11 components of name are used and the last five are left unused
C++ Programming: Program DesignIncluding Data Structures, Fourth
C-Strings (Character Arrays)
(continued)
C++ Programming: Program DesignIncluding Data Structures, Fourth
String Comparison
- C-strings are compared character by character using the collating sequence of the system
- If we are using the ASCII character set
- "Air" < "Boat"
- "Air" < "An"
- "Bill" < "Billy"
- "Hello" < "hello"
C++ Programming: Program DesignIncluding Data Structures, Fourth
Reading and Writing Strings
- Most rules that apply to arrays apply to C-strings as well
- Aggregate operations, such as assignment and comparison, are not allowed on arrays
- Even the input/output of arrays is done component-wise
- The one place where C++ allows aggregate operations on arrays is the input and output of C- strings (that is, character arrays)
C++ Programming: Program DesignIncluding Data Structures, Fourth
String Input
- cin >> name; stores the next input C-string into name
- To read strings with blanks, use get:
cin.get(str, m+1);
- Stores the next m characters into str but the newline character is not stored in str
- If the input string has fewer than m characters, the reading stops at the newline character
C++ Programming: Program DesignIncluding Data Structures, Fourth
Specifying Input/Output Files at
Execution Time
- You can let the user specify the name of the input and/or output file at execution time:
C++ Programming: Program DesignIncluding Data Structures, Fourth
string Type and Input/Output
Files
- Argument to the function open must be a null- terminated string (a C-string)
- If we use a variable of type string to read the name of an I/O file, the value must first be converted to a C-string before calling open
- Syntax:
strVar.c_str() where strVar is a variable of type string