Bitp 1113 Programming Technique: Lecture 10 - String and File Processing
Bitp 1113 Programming Technique: Lecture 10 - String and File Processing
1
LEARNING OUTCOMES
At the end of this lecture, you should be able to
use functions in cctype, cstring and string
classes to manipulate character and string
explain the use of files in storing data
describe the important components needed in writing
C++ code for file processing
2
C-STRINGS
C-string: sequence of characters stored in
adjacent memory locations and terminated
by NULL character
The C-string
"Hi there!"
would be stored in memory as shown:
H i t h e r e ! \0
3
CHARACTER TESTING
4
FROM PROGRAM 10-1
5
CHARACTER CASE CONVERSION
Require cctype header file
Functions:
toupper: if char argument is lowercase letter, return
uppercase equivalent; otherwise, return input unchanged
char ch1 = 'H';
char ch2 = 'e';
char ch3 = '!';
cout << toupper(ch1); // displays 'H'
cout << toupper(ch2); // displays 'E'
cout << toupper(ch3); // displays '!'
6
CHARACTER CASE CONVERSION
Functions:
tolower: if char argument is uppercase letter, return
lowercase equivalent; otherwise, return input unchanged
char ch1 = 'H';
char ch2 = 'e';
char ch3 = '!';
cout << tolower(ch1); // displays 'h'
cout << tolower(ch2); // displays 'e'
cout << tolower(ch3); // displays '!'
7
C-STRINGS
8
C-STRINGS
9
10
LIBRARY FUNCTIONS FOR WORKING WITH C-STRINGS
11
LIBRARY FUNCTIONS FOR WORKING WITH C-STRINGS
Functions:
strlen(str): returns length of C-string str
char city[SIZE] = "Missoula";
cout << strlen(city); // prints 8
strcat(str1, str2): appends str2 to the
end of str1
char location[SIZE] = "Missoula, ";
char state[3] = "MT";
strcat(location, state);
// location now has "Missoula, MT"
12
LIBRARY FUNCTIONS FOR WORKING
WITH C-STRINGS
Functions:
strcpy(str1, str2): copies str2 to str1
13
LIBRARY FUNCTIONS FOR WORKING WITH C-STRINGS
Functions:
strlwr() function is used to convert a string to lowercase.
14
LIBRARY FUNCTIONS FOR WORKING WITH C-STRINGS
Example :
char faculty1[10] = “FTMK ";
char faculty2[10];
strcpy(faculty2,strlwr(faculty1));
cout << faculty2;
Output :
ftmk
15
LIBRARY FUNCTIONS FOR WORKING WITH C-STRINGS
16
LIBRARY FUNCTIONS FOR WORKING WITH C-STRINGS
Example :
char faculty1[10] = “ftmk ";
strcpy(faculty2,strupr(faculty1));
cout << faculty2;
Output :
FTMK
17
C-STRING INSIDE A C-STRING
Function:
strstr(str1, str2): finds the first
occurrence of str2 in str1. Returns a pointer
to match, or NULL if no match.
char river[] = "Wabash";
char word[] = "aba";
cout << strstr(state, word);
// displays "abash"
18
STRING/NUMERIC CONVERSION
FUNCTIONS
require cstdlib header file
FUNCTION PARAMETER ACTION
atoi C-string converts C-string to an int value, returns
the value
atol C-string converts C-string to a long value, returns
the value
atof C-string converts C-string to a double value,
returns the value
itoa int,C-string, converts 1st int parameter to a C-string,
int stores it in 2nd parameter. 3rd parameter is
base of converted value
19
STRING/NUMERIC CONVERSION
FUNCTIONS
int iNum;
long lNum;
double dNum;
char intChar[10];
iNum = atoi("1234"); // puts 1234 in iNum
lNum = atol("5678"); // puts 5678 in lNum
dNum = atof("35.7"); // puts 35.7 in dNum
itoa(iNum, intChar, 8); // puts the string
// "2322" (base 8 for 123410) in intChar
20
STRING/NUMERIC CONVERSION FUNCTIONS - NOTES
21
WRITING YOUR OWN C-STRING HANDLING FUNCTIONS
22
FROM PROGRAM 10-9
23
FROM PROGRAM 10-10
24
THE C++ STRING CLASS
25
26
INPUT INTO A STRING OBJECT
27
28
INPUT INTO A STRING OBJECT
29
STRING COMPARISON
30
31
OTHER DEFINITIONS OF C++ STRINGS
Definition Meaning
string name; defines an empty string object
string myname("Chris"); defines a string and initializes it
string yourname(myname); defines a string and initializes it
string aname(myname, 3); defines a string and initializes it with first 3
characters of myname
32
STRING OPERATORS
OPERATOR MEANING
>> extracts characters from stream up to whitespace, insert
into string
<< inserts string into stream
= assigns string on right to string object on left
+= appends string on right to end of contents on left
+ concatenates two strings
[] references character in string using array notation
>, >=, <, relational operators for string comparison. Return true or
<=, ==, != false
33
STRING OPERATORS
string word1, phrase;
string word2 = " Dog";
cin >> word1; // user enters "Hot Tamale” word1 has "Hot"
phrase = word1 + word2; // phrase has "Hot Dog"
phrase += " on a bun";
for (int i = 0; i < 16; i++)
cout << phrase[i]; // displays
// "Hot Dog on a bun"
34
35
STRING MEMBER FUNCTIONS
Are behind many overloaded operators
Categories:
assignment: assign, copy, data
modification: append, clear, erase, insert,
replace, swap
space management: capacity, empty, length,
resize, size
substrings: find, substr
comparison: compare
See Table 10-7 for a list of functions
36
STRING MEMBER FUNCTIONS
37
38
Using Files for Data Storage
39
USING FILES FOR DATA STORAGE
Can use files instead of keyboard, monitor screen
for program input, output
Allows data to be retained between program runs
Steps:
Open the file
Use the file (read from, write to, or both)
Close the file
40
FILES: WHAT IS NEEDED
Use fstream header file for file access
File stream types:
ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file
Define file stream objects:
ifstream infile;
ofstream outfile;
41
OPENING FILES
Create a link between file name (outside the program) and file
stream object (inside the program)
Use the open member function:
infile.open("inventory.dat");
outfile.open("report.txt");
Filename may include drive, path info.
Output file will be created if necessary; existing file will be erased
first
Input file must exist for open to work
42
TESTING FOR FILE OPEN ERRORS
Can test a file stream object to detect if an open
operation failed:
infile.open("test.txt");
if (!infile)
{
cout << "File open failure!";
}
Can also use the fail member function
43
USING FILES
Can use output file object and << to send data to
a file:
outfile << "Inventory report";
Can use input file object and >> to copy data
from file to variables:
infile >> partNum;
infile >> qtyInStock >> qtyOnOrder;
44
USING LOOPS TO PROCESS FILES
The stream extraction operator >> returns true
when a value was successfully read, false
otherwise
45
CLOSING FILES
Use the close member function:
infile.close();
outfile.close();
Don’t wait for operating system to close files at
program end:
may be limit on number of open files
may be buffered output data waiting to send to file
46
LETTING THE USER SPECIFY A FILENAME
The open member function requires that you
pass the name of the file as a null-terminated
string, which is also known as a C-string.
String literals are stored in memory as null-
terminated C-strings, but string objects are not.
47
LETTING THE USER SPECIFY A FILENAME
string objects have a member function named
c_str
It returns the contents of the object formatted as a
null-terminated C-string.
Here is the general format of how you call the c_str
function:
stringObject.c_str()
48
LETTING THE USER SPECIFY A FILENAME IN PROGRAM 5-24
Continued…
49
LETTING THE USER SPECIFY A FILENAME IN PROGRAM 5-24
50
ASK YOURSELF
Do you know how to use functions in the cctype,
cstring and string classes to manipulate
characters and strings?
Can you explain why file processing is useful?
Do you know the three important steps in writing
the code for file processing?
51