Download presentation
Presentation is loading. Please wait.
Published byAshlyn Spencer Modified over 5 years ago
1
Chapter 8 (Part 3) Library Classes for Strings (P.405)
2
String Concatenation Good afternoon. Bob. Good afternoon. Charlie.
#include <iostream> using std::cout; int main() { char a[] = "Good afternoon. "; char b[] = "Bob. "; char c[] = "Charlie. "; char newline[] = "\n"; char str[80] = ""; strcpy(str, a); strcat(str, b); strcat(str, newline); strcat(str, a); strcat(str, c); cout << str; return 0; } Good afternoon. Bob. Good afternoon. Charlie.
3
Powerful C++ Class #include <iostream> #include <string> using std::cout; using std::string; int main() { string a = "Good afternoon. "; string b = "Bob. "; string c = "Charlie. "; string newline = "\n"; string str; str = a + b + newline + a + c + newline; cout << str; return 0; }
4
Strings C language only has null-terminated strings which is stored as character arrays. char name[5] = "Mary"; C++ provides a string data type which is much easier to use. This class provides a bunch of powerful functions.
5
Creating String Objects
string sentence = "This sentence is false."; string sentence("This sentence is false."); string bees(7, 'b'); string bees("bbbbbbb"); string letters(bees); string part(sentence, 5, 11); string part("sentence is"); the first character is at index position 0 string names[] = { "Alice", "Bob" }; string arrays
6
Input a string Read a character string into a string object:
string sentence; cin >> sentence; However, cin will ignores leading whitespaces, and also terminates input when you enter a space, so for the input “This is a book”, only “This” is read into the object. Use the getline() function: getline(cin, sentence); ifstream fsIn("abc.txt"); getline(fsIn, sentence); the source of the input the destination for the input
7
Concatenating Strings
Use the + operator to concatenate two string objects or a string object and a string literal. #include <iostream> #include <string> using std::cout; using std::endl; using std::string; int main() { string sentence1 = "This"; string sentence2 = "That"; string combined = sentence1 + "\n" + sentence2; cout << combined << endl; return 0; } This That
8
Concatenating Strings (2)
You can also use the + operator to join a character to a string object sentence = sentence + '\n'; sentence += '\n'; sentence += "\n"; Length of a string sentence.length() // returns an integer sentence.empty() // returns true or false Ex8_14.cpp (P.408) size_t is defined using typedef statement to be equivalent to unsigned int. (P.154)
9
Accessing Strings Access a character in a string
string sentence("Too many cooks spil the broth."); for (int i = 0; i < sentence.length(); i++) { if (' ' == sentence[i]) sentence[i] = '*'; } Use the at() member function if (' ' == sentence.at(i)) sentence.at(i) = '*'; Subscripting is faster, but the validity of the index is not checked.
10
Access a substring in a string
Extract a part of an existing string object as a new string object. string sentence("Too many cooks spoil the broth."); string w = sentence.substr(4,10); // Extracts "many cooks"
11
Modifying Strings (1) Add one or more characters to the end of a string. string phrase("The higher"); string word("fewer"); phrase.append(1, ' '); // Append one space phrase.append("the "); // Append a string literal phrase.append(word); // Append a string object phrase.append(2, '!');// Append two exclamation marks When you call append(), the function returns a reference to the object, so you could write the above calls in a single statement: phrase.append(1, ' ').append("the ").append(word).append(2, '!');
12
Modifying Strings (2) Insert a string in the interior of another string: (P.412) string word("ABCDEF"); string test("==="); word.insert(3, test); // word will become "ABC===DEF" Swap the contents of two string objects: string phrase("The more the merrier."); string query("Any"); query.swap(phrase);
13
Modifying Strings (3) Replace part of a string object
string text("ABCDEF"); text.replace(2, 3, "->"); text will become “AB->F” Replacement with a null string will essentially delete that part. text = "AB->F"; text.replace(2, 2, ""); text will become “ABF”
14
Comparing Strings Operator overloading has been implemented for
== != < <= > >= When two corresponding characters are compared, their ASCII codes determine which one is less than the other. "USA" < "unique" If no character pairs are found to be different, the string with fewer characters is less. "book" < "books"
15
Ex8_15.cpp (P.415) in main(): nstrings: # of input strings maxwidth: maximum length of input strings string* sort(string* strings, size_t count) Actually the return type can be void in this example.
16
Search Strings Four versions of the find() function:
string phrase("So near and yet so far"); string str("So near"); cout << phrase.find(str) << endl; // Outputs 0 (starting position) cout << phrase.find("so far") << endl; // Outputs 16 cout << phrase.find("so near") << endl; // Outputs string::npos = on MS VC++ The function returns the value string::npos if the item was not found. The value of string::npos may vary with different C++ compilers, so you should always use string::npos and not the explicit value.
17
Search Strings (2) Searching from a specified position:
string phrase("ABCDEABCDEABCDE"); cout << phrase.find("A"); // Outputs 0 cout << phrase.find("A", 3); // Outputs 5 cout << phrase.find("A", 11); // Outputs string::npos =
18
Handling Chinese Characters
#include <iostream> #include <string> using std::cout; using std::string; int main() { string myString = "暨南大學"; string str2 = "中文"; cout << myString << myString.length() << '\n'; cout << str2.substr(3,3) << myString.substr(6,3) << '\n'; return 0; // length() size() are measured in } // bytes, not characters.
19
Exercise: Splitting Chinese Characters
Write a program to read a line from the user. That line may contain both English and Chinese characters, and punctuation and spaces. Store the line as a string. Then print each character in a separate line. e.g., msg = "物聯網(IoT)"; 物 聯 網 ( I o T )
20
File I/O
21
Using Input/Output Files
A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide input data to a program or receive output data from a program, or both; must reside in Project directory (not necessarily the same directory as the .cpp files) must be opened before it is used.
22
C Functions for File I/O
In function-oriented programming, we use the following functions to access disk files: fopen() fclose() fread() fwrite() fprintf() In object-oriented programming, we use a well-prepared class “fstream”.
23
C++ Classes for Input / Output
stream - a sequence of characters interactive (iostream) cin - input stream associated with keyboard. cout - output stream associated with display. file (fstream) ifstream - defines new input stream (normally associated with a file). ofstream - defines new output stream (normally associated with a file).
24
Input File-Related Functions
#include <fstream> ifstream fsIn; fsIn.open("fname.txt") connects stream fsIn to the external file "fname.txt". fsIn >> c; //Behaves just like cin fsIn.close() disconnects the stream and associated file.
25
Output File-Related Functions
#include <fstream> ofstream fsOut; fsOut.open("fname.txt") connects stream fsOut to the external file "fname.txt". fsOut << c; //Behaves just like cout fsOut.close() disconnects the stream and associated file.
26
Example 1 #include <iostream> #include <fstream> using namespace std; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName, ios::out); Students << FirstName << "\n" << LastName << "\n" << Age; cout << "\n\n"; return 0; } The file will be created in the directory where your “.cpp” file resides. e.g. “D:\VisualStudio2010\Projects\YourProject\YourProject”
27
Example 2 #include <iostream> #include <fstream> using std::cin; using std::cout; using std::ofstream; int main() { char FirstName[30], LastName[30]; int Age; // char FileName[20]; string FileName; // Length may be greater than 20 if full pathname is specified. cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName); Students << FirstName << "\n" << LastName << "\n" << Age; Students.close(); return 0; }
28
Example 3: Output to a File
#include <fstream> #include <iostream> using std::cout; using std::endl; using std::ofstream; int main() { ofstream Student("message.txt"); Student << "HELLO\n"; Student << "HI\n"; return 0; }
29
Example 4 – Input from a File
#include <iostream> #include <fstream> using std::cin; using std::cout; using std::ifstream; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter the name of the file you want to open: "; cin >> FileName; ifstream Students(FileName); Students >> FirstName >> LastName >> Age; Students.close(); cout << "\nFirst Name: " << FirstName; cout << "\nLast Name: " << LastName; cout << "\nEnter Age: " << Age; cout << "\n\n"; return 0; }
30
Exercise: ifstream There are 100 lines in "/home2/ncnu/ifstream100.dat". There is exact one integer in a line. Write a program and use the "ifstream" class to read data from this file. Calculate the sum of these numbers. Extend your program to read the filename from the user. It should be able to handle unlimited number of lines with the following indefinite loop: while (fsIn >> n) { sum += n; count++; } Test your program with /home2/ncnu/ifstream100.dat /home2/ncnu/ifstream5.dat
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.