Presentation is loading. Please wait.

Presentation is loading. Please wait.

Files in C++ Week 2 Computer Programming II 1.

Similar presentations


Presentation on theme: "Files in C++ Week 2 Computer Programming II 1."— Presentation transcript:

1 Files in C++ Week 2 Computer Programming II 1

2 Introduction to File I/O in C++ File I/O Streams File Open Modes
Lecture Objectives Introduction to File I/O in C++ File I/O Streams File Open Modes Performing File I/O Closing File Streams Binary File I/O Random Access File I/O Computer Programming II 2

3 Concepts of Files Computer Programming II
Files are used for Permanent Storage of Data. Files are stored on secondary storage devices such as magnetic disks, optical disks and tapes. Computer Secondary Storage Devices Files OS Computer Programming II 3

4 Data Hierarchy Computer Programming II
Bit : smallest data items in a computer ( 0 and 1) Byte : Sequence of Bits (eight Bits) Data : Raw Fact Field : Collection of Data Record : Collection of Fields File : Collection of Records John Idris Junaid File Fatimah J u n a i d Record Field Byte (ASCII character of J) 1 Bit Computer Programming II 4

5 C++’s view of a file of n bytes
File and Streams C++ views each file simple as a sequence of bytes. Each file ends with an end-of-file marker When a file is opened, an object is created and a stream is associated with the object. To perform file processing in C++, the header files <iostream> and <fstream> must be included. Files are opened by creating objects of these stream classes. relationships of file stream classes Next Slide C++’s view of a file of n bytes 1 2 3 4 5 6 7 n-1 End-of-file marker Computer Programming II 5

6 Hierarchy of file stream classes
ios istream ostream ifstream iostream ofstream fstream There are usually several standard streams opened automatically for you by C++... stdin - keyboard (or console) stdout - screen (normal program output) stderr - screen (error messages) stdprn - printer stdaux - serial communications stdprn and stdaux are not available on all systems. Computer Programming II 6

7 Opening files To open the file after the file stream has been created,
we use the function open() ofstream fout; // Create a file output stream fout.open(“myFile.txt”); // Associate the stream with // the file “myFile.txt” This is used if we want to use the same stream toaccess multiple files, or if we want to access the same file multiple times with lengthy breaks in-between (during which we will “close” the file) Fist, MMU, Melaka

8 File I/O Stream To initialize the file stream when it is created, simply pass the name of the file as an argument to the ifstream fin(“myFile.txt”); // Create a file input // stream and associate it // with “myFile.txt” This is an example of a constructor – an aspect of object-oriented programming that we will discuss later In essence, it tells the program to immediately associate this file stream with “myFile.txt” when it is first created Fist, MMU, Melaka

9 Example 1 #include <fstream.h> void main(){ char ch; ifstream infile("MYFILE.DAT"); while (infile) { infile.getch(ch); cout << ch; } } Fist, MMU, Melaka

10 Example 2 #include <fstream.h> void main(){ char ch; ifstream infile("IN.DAT"); ofstream outfile("OUT.DAT"); while (infile) { infile.getch(ch); outfile.put(ch); } } Fist, MMU, Melaka

11 File Open Modes Open the File
Modes of Opening a file ios::app Write all output to the end of the file. ios::ate Open a file for output and move to the end of the file. ios::in Open a file for input. ios::out Open a file for output. ios::binary Open a file in binary mode ios::trunc Discard the file's contents if it exists. ios::nocreate If the file does not exists, open fails. ios::noreplace If the file exists, the open fails. Fist, MMU, Melaka

12 File Open Modes Thus, if we wanted to open a file for input in binary mode, we could do it using any of the following methods: ifstream fin; fin.open(“myFile.txt”, ios_base::in | ios_base::binary); ifstream fin(“myFile.txt”, ios_base::in | ios_base::binary); fstream fin(“myFile.txt”, Fist, MMU, Melaka

13 File Open Modes However, generally we will use the default arguments
Stream Type Default Arguments provided: ifstream ios_base::in ofstream ios_base::out | ios_base::trunc fstream ios_base::in | ios_base::out The lack of a truncation flag for fstream’s means that for this type of file stream, by default, a new file will not be created if one does not already exist Fist, MMU, Melaka

14 File Open Modes When attempting to perform file I/O, it is important that we verify the state of a file stream each time we attemptto associate it with a file For example, if we try to associate a file input stream with a file that doesn’t exist, we’re going to run into problems While it is possible to do this by checking the flags that were introduced for general I/O, the preferred way is to use the function is_open(), which returns true if the file has been successfully opened and associated with our file stream Fist, MMU, Melaka

15 File Open Modes Thus, the following general structure should be used for file I/O: ofstream fout(“myFile.txt”); if (fout.is_open()) { // Perform file I/O } else // Error-related code Fist, MMU, Melaka

16 Performing File I/O ofstream fout(“myFile.txt”); if (fout.is_open()) {
Once a file stream has been created and associated with a particular file, I/O is performed in the exact same manner as it was for general I/O, using the insertion and extraction operators Output example: ofstream fout(“myFile.txt”); if (fout.is_open()) { fout << “Hello” << endl; } Because file streams are based on general I/O streams, all of the same manipulators and functions can be used (such as endl) As before, C++ uses pass-by reference to pass the new file stream to the insertion operator Fist, MMU, Melaka

17 Input Example Because file streams are based on general I/O streams, all of the same manipulators and functions can beused (such as endl) ifstream fin(“myFile.txt”); if (fin.is_open()) char buffer[256]; fin.getline(buffer, 256); File input can be read in line-byline just as standard input can Fist, MMU, Melaka

18 Closing File Stream To explicitly close a file stream use close( )
In C++, it is not necessary to explicitly close a file stream (or any type of stream, for that matter), as streams are automatically closed when they go out of scope int main() { ofstream fout(“myFile.txt”); } At this point, fout is no longer in-scope, so the file stream’s association with “myFile.txt” will be terminated (the stream will be “closed”) after which the stream object itself will be deallocated Fist, MMU, Melaka To explicitly close a file stream use close( )

19 File Close - Example ofstream fout (“myFile.txt”); if (fout.is_open())
{ fout << “Hello” << endl; fout.close(); // Close the file stream }… fout.open(“myFile.txt”, ios_base::out | ios_base::app); // Reopen the file stream fout … } Fist, MMU, Melaka

20 File Closing It is important to realize that closing a file stream (via the function close() ) only serves to terminate the The file stream object continues to exist The state of the file stream is maintained at whatever it was Thus, if we are going to reuse a file stream with multiple files, it is important to reset the state (in case of an earlier failure) Fist, MMU, Melaka

21 File Closing Streams Thus, we should rewrite the previous example as:
ofstream fout (“myFile.txt”); if (fout.is_open()) { fout << “Hello” << endl; fout.close(); // Close the file stream } fout.clear(); // Reset the file stream’s state fout.open(“myFile.txt”, ios_base::out | ios_base::app); // Reopen the file stream fout << “How are you today?” << endl; … } Fist, MMU, Melaka

22 Binary File When we introduced C++ I/O, we said that input and output streams converted between the programs internal representation for data objects and characters (such as from the internal representation for the number 15 to the characters ‘1’ and ‘5’ and vice versa) Reason for doing this: to translate between the internal binary representation and a format that is easier to understand for humans Thus, C++ allows us to perform binary file I/O, in which we store and retrieve the original binary representation for data objects Fist, MMU, Melaka

23 Advantages & Disadvantages
The advantages to binary file I/O include: No need to convert between the internal representation and a character-based representation Reduces the associated time to store/retrieve data Possible conversion and round-off errors are avoided Storing data objects in binary format usually takes less space (though this depends on the nature of the data) Disadvantages: The file is not easily readable by humans Portability becomes an issue, as different operating systems (and even different compilers) may use different internal representations Fist, MMU, Melaka

24 ifstream fin (“myFile2.txt”, ios_base::in | ios_base::binary);
Creating a Binary File Creating a stream that will handle binary I/O is as simple as setting a flag Create a binary file output stream: ofstream fout (“myFile.txt”, ios_base::out |ios::trunc | ios_base::binary); Create a binary file input stream: ifstream fin (“myFile2.txt”, ios_base::in | ios_base::binary); Fist, MMU, Melaka

25 Binary File It’s important to realize that the ios_base::binary flag may be rejected by some systems (specifically, UNIX systems) This does not imply that we cannot do binary I/O in UNIX! Certain operating systems (such as those based on MS-DOS) have two file formats (one for text and one for binary) – if we try to do binary I/O on those systems while in text mode, we can run into problems If your compiler returns an error because it doesn’t recognize the ios_base::binary flag, simply remove it Fist, MMU, Melaka

26 Binary File I/O Two functions are used : READ & WRITE write()
Lets us write a specified number of characters to an output stream does a straight byte-by-byte copy fout.write(reinterpret_cast<char *>(&obj); sizeof obj); Read ( ) Lets us read a specified number of characters to an output stream does a straight byte-by-byte read fin.read(reinterpret_cast<char *>(&obj); sizeof obj); Fist, MMU, Melaka

27 Binary File I/O read() call is virtually identical to the write() call – in this case, we are extracting the exact number of bytes required to define an object of type obj and placing them in the specified memory location When performing binary input, be sure to check the state of the stream after each call, as you may encounter an end-of-file (EOF), this can be done by calling the function eof() Fist, MMU, Melaka

28 Example - Write and Read
#include <iostream.h> #include <fstream.h> //required for file I/O #include <stdlib.h> // required for exit() and atoi #include <string.h> #define FILE_IN "TestBinaryOutput.dat" //we'll write and read the same file #define FILE_OUT "TestBinaryOutput.dat" struct Person { char name[50]; int age; char sex; // M or F }; Fist, MMU, Melaka Program Cont.. Next Slide

29 Example - Write and Read
int main() { Person people; strcpy(people.name,"Claire J"); people.age = 25; people.sex = 'F'; ofstream output; //setup output stream object output.open(FILE_OUT, ios::out|ios::binary); output.write((char *) &people, sizeof(Person) ); output.close(); Person Newperson; ifstream input; //setup output stream object input.open(FILE_IN, ios::out|ios::binary); input.read((char *) &Newperson, sizeof(Person) ); cout << "\n The new person is " << Newperson.name; cout << "\n His/Her sex is " << Newperson.sex; cout << "\n His/Her age is " << Newperson.age; input.close(); return 0; } Write Read Fist, MMU, Melaka

30 Program Cont.. Next Slide
Example 2 Program Cont.. Next Slide #include <iostream.h> #include <fstream.h> //required for file I/O #include <stdlib.h> // required for exit() and atoi #include <string.h> #define FILE_IN "BinaryOutput2.dat" //we'll write and read the same file #define FILE_OUT "BinaryOutput2.dat" struct Person { char name[50]; int age; char sex; // M or F }; int main() { Person people; strcpy(people.name,"Claire J"); people.age = 25; people.sex = 'F'; int numbers[4] = {23, 235, 36, 9433 }; int counter = 43; ofstream output; Fist, MMU, Melaka

31 Example 2 - Cont... output.open(FILE_OUT, ios::out|ios::binary);
output.write((char *) &people, sizeof(Person) ); output.write((char *) &numbers, sizeof(numbers) ); output.write((char *) &counter, sizeof(int) ); output.close(); Person Newperson; int Newnums[4]; int Newcounter; ifstream input; //setup output stream object input.open(FILE_IN, ios::out|ios::binary); input.read((char *) &Newperson, sizeof(Person) ); input.read((char *) &Newnums, sizeof(Newnums) ); input.read((char *) &Newcounter, sizeof(int) ); cout << "\n The new person is " << Newperson.name << Newperson.sex << Newperson.age << Newnums[0] << "," << Newnums[1]<< "," << Newnums[2] << "," << Newnums[3]; cout << "\n Newcounter is " << Newcounter; input.close(); return 0; } Write Declaration Read Fist, MMU, Melaka

32 Random Access File Thus far, we have assumed that all of our file access(both input and output) will be in sequential order In many cases, we would rather access specific parts of a data source/destination For example, imagine that we have a file in which we store all of the information about a particular user’s profile. If the user wants to change their name, it would be preferable to be able to seek to that location in the file, change the name, and be done with it (rather than having to read in the entire file and rewrite it again – just to change a few characters) Fist, MMU, Melaka

33 Random Access Files - Cont...
C++’s view of random-access file composed of fixed-length records (each record is 100 bytes long) Data can be inserted in a random-access file without destroying other data in the file. Data stored previously also can be updated or deleted without rewriting the entire file. 100 200 300 400 bytes byte offsets Fist, MMU, Melaka

34 Random Access Files Files have a notion of a current position – the location at which you write to or read from the file The input pointer identifies the current position for input (the location at which the next write will occur) The output pointer identifies the current position for output (the point at which the next read will occur) By default, these “pointers” are automatically set to the beginning or end of a file when it is first opened (depending on whether the ios_base::app or ios_base::trunc flag is set) Fist, MMU, Melaka

35 Random Access Files With random access file I/O, we are able to change the current position of a file without having to read all of the data in-between In reality, the input and output pointers are identifying locations in the file stream buffers, rather than in the actual file but conceptually, it’s easier to think of them as identifying locations in the file itself Random access file I/O can be used for both text files and binary files However, random access in text files can be tricky, because of unexpected conversions Fist, MMU, Melaka

36 Functions for File Pointer Manipulations
. The C++ I/O system supports four functions for setting a pointer seekg() Ifstream Moves get file pointer to a specific location seekp() ofstream Moves put file pointer to a specific location tellg() ifstream Returns the current position of the get pointer tellp() ofstream Returns the current position of the put pointer The seekp() and tellp() deal with the put pointer, while seekg() and tellg() deal with the get pointer. prototypes: istream &seekg (long offset, seek_dir origin = ios::beg); ostream &seekp (long offset, seek_dir origin = ios::beg); Both functions set a file pointer to a certain offset relative to the specified origin. The second parameter origin, represents the reference point from where the offset is measured. Fist, MMU, Melaka

37 File Seek Origin Example Seek Calls and their actions Next Slide
. Origin value Seek From … ios::beg seek from beginning of file ios::cur seek from current location ios::end seek from end of file Example infile.seekg(20, ios::beg); or infile.seekg(20); outfile.seekp(20, ios::beg); outfile.seekp(20); moves the file pointer to the 20th byte in the file, infile. After this, if a read operation is initiated, the reading starts from the 21st item within the file. moves the file pointer to the 20th byte in the file outfile. After this, if write operation is initiated, the writing starts from the 21st item within the file. Fist, MMU, Melaka

38 Seek Calls and their Actions
Seek call Action performed outfile.seekg(0, ios::beg) Go to the beginning of the file outfile.seekg(0, ios::cur) Stay at the current file outfile.seekg(0, ios::end) Go to the end of the file outfile.seekg(n, ios::beg) Move to (n+1) byte location in the file outfile.seekg(n, ios::cur) Move forward by n bytes from current position outfile.seekg(-n, ios::cur) Move backward by n bytes from current position outfile.seekg(-n, ios::end) Move forward by n bytes from the end infile.seekg(n, ios::beg) Move write pointer to (n+1) byte location infile.seekg(-n, ios::cur) Move write pointer backward by n bytes Fist, MMU, Melaka

39 Returns the value of the Output Pointer
Example Moves the Output Pointer to a Specified Location Returns the value of the Output Pointer ofstream fout(“myFile.txt”); if (fout.is_open()) { fout << “Hello, this is a file.” << endl; fout.seekp(15); fout << “not a file“; ofstream fout(“myFile.txt”); if (fout.is_open()) { fout << “Hello, this is a file.” << endl; fout.seekp(fout.tellp() – static_cast<streampos>(8)); fout << “not a file“; Fist, MMU, Melaka

40 Example 2 - Seekp Moves the output pointer by the specified offset starting from the specified direction ofstream fout(“myFile.txt”); if (fout.is_open()) { fout << “Hello, this is a file.” << endl; fout.seekp(-8, ios_base::cur); fout << “not a file“; The call to seekp in this example could also be rewritten as: fout.seekp(-8, ios_base::end); or fout.seekp(15, ios_base::beg); Fist, MMU, Melaka

41 Examples for tellg & seekg
Returns the value of the input pointer ifstream fin(“myFile.txt”); if (fin.is_open()) { char c; fin.seekg(fin.tellg() – static_cast<streampos>(5)); fin >> c; … } Moves the input pointer by the specified offset starting from the specified direction ifstream fin(“myFile.txt”); if (fin.is_open()) char c; fin.seekg(5, ios_base::cur); fin >> c; Fist, MMU, Melaka

42 Program for Writing into a Random Access File
The combination of ostream functions seekp and write to store data at exact locations in the file. Function seekp sets the “put” file position pointer to a specific position in the file, then write outputs the data. Example struct StudentData { int studentId, accountNumber; char lastName[15]; char firstName[10]; double balance; }; int main() { ofstream OutStudent( "Student.dat", ios::binary ); if ( !OutStudent ) { cerr << "File could not be opened." << endl; exit( 1 ); } cout << "Enter account number " << "(1 to 100, 0 to end input)\n? "; StudentData student; Cont in Next slide Fist, MMU, Melaka

43 Program Cont…. cin >> student.accountNumber;
while (student.accountNumber > 0&&student.accountNumber<= 100 ) { cout << "Enter studentId, lastname, firstname, balance\n "; cin >> student.studentId>>student.lastName >> student.firstName >> student.balance; OutStudent.seekp( ( student.accountNumber - 1) * sizeof(StudentData ) ); OutStudent.write(reinterpret_cast<const char *>( &student ),sizeof( StudentData )); cout << "Enter account number\n"; } return 0; } Fist, MMU, Melaka

44 Program to Read Data From a Random Access File
void Output( ostream&, const StudentData & ); struct StudentData { int studentId, accountNumber; char lastName[15]; char firstName[10]; double balance; }; int main() { ifstream InStudent( "Student.dat", ios::in ); if ( !InStudent ) { cerr << "File could not be opened." << endl; exit( 1 ); } StudentData student; Cont in Next slide Fist, MMU, Melaka After creating a random access file it can read sequentially

45 Program Cont... InStudent.read( reinterpret_cast<char *>( &student ), sizeof( StudentData ) ); while ( InStudent && !InStudent.eof( ) ) { if ( student.accountNumber != 0 ) cout<<student.studentId << student. countNumber << student. lastName << student. firstName << student. balance << '\n'; InStudent.read( reinterpret_cast<char *>( &student ),sizeof( StudentData ) ); } return 0; Fist, MMU, Melaka

46 C++ Standard Library - String
Overview : The C++ Standard Library is made up of a variety of classes deemed useful enough to the general programming population that they should be made a “standard” part of C++ We have already encountered parts of the Standard Library, such as the IOStream classes The Standard Library includes 32 C++ header files, plus 18 header files that define facilities of the original C library Fist, MMU, Melaka

47 Header Files The 18 C header files: C header files are simply their
names in C, prefixed with the letter ‘c’ <algorithm> <bitset> <complex> <deque> <exception> <fstream> <functional> <iomanip> <ios> <iosfwd> <iostream> <istream> <iterator> <limits> <list> <locale> <stack> <stdexcept> <streambuf> <string> <typeinfo> <utility> <valarray> <vector> <map> <memory> <new> <numeric> <ostream> <queue> <set> <cassert> <cctype> <cerno> <cfloat> <ciso646> <climits> <clocale> <cmath> <csetjmp> <csignal> <cstdard> <cstddef> <cstdio> <cstdlib> <cstring> <ctime> <cwchar> <cwctype> Fist, MMU, Melaka

48 Overview The components of the C++ Standard Library are defined within the std namespace, so include using namespace std; A typical C++ program file might begin as follows: #include <iostream> // Include I/O stream facilities #include <string> // Include string class using namespace std; // Access the std namespace In order to solve string related problems ( such as array overflow ) a string class was added to C and an advanced class <string> to C++. Fist, MMU, Melaka

49 String Class Many of the capabilities of the new string class are made possible by the object-oriented features of C++ String Object : It is an array of characters terminated by the null character (‘\0’) However, the C++ string object “repackages” our simple character array in such a way as to provide a wide selection of new, easier ways to manipulate Fist, MMU, Melaka

50 Creating Strings Strings are created using constructors as follows:
string() Creates a new, empty string (size 0) string x; string* x = new string; string(const char* s) Creates a new string and initializes it to the null-character terminated array of characters pointed to by s string x(“hello”); string* x = new string(“hello”); Fist, MMU, Melaka

51 Creating Strings string(size_type n, char c) Creates a new string consisting of n instances of the character c string x(10, ‘a’); string* x = new string(10, ‘a’); Note : C++ does not allow you to initialize a string with a single character argument string x(‘a’); // Error Instead, the above constructor must be used string x(1, ‘a’); Fist, MMU, Melaka

52 Creating Strings string(const string& s, size_type pos = 0, size_type n = npos) Creates a new string and initializes it to the string s, starting at position pos and proceeding for n characters or to the end of s (whichever comes first) string x(“hello”); string y(x, 3, 2); // String “lo” string* y = new string(x, 3, 2); You can also create strings by using an overloaded version of the assignment operator (‘=’): string x = “hello”; string y = x; In both of the cases, a new string is created and initialized with a copy of the string on the right side of the assignment operator Fist, MMU, Melaka

53 Program 1 - String with overloaded operators
#include <iostream> #include <string> using namespace std; int main() { string S1(“How are you?”),s2,s3; char myoldstring[20]=“Howdy Partner”; string S4(myoldstring); s2 = “Do you love C++”; s3 = s1+ s2; cout<<s1<<endl; cout<<s2<<endl; cout<<s3<<endl; cout<<s4<<endl; s1 = “All done with strings”; cout <<s1<<endl; return 0; } Output: How are you? Do you love C++ How are you?Do you love C++ Howdy Partner All done with strings Fist, MMU, Melaka

54 Comparisons The relationship between two string’s can be evaluated by performing a lexical comparison between them This means that when we compare strings, we are actually comparing them based on numeric representations of the characters which they contain (generally, the ASCII codes) relationship determined by the first pair of characters that differ All six comparison operators can be used to compare string’s (==, !=, <, >, <=, >=) Fist, MMU, Melaka

55 Program 2 - Comparison #include <iostream>
#include <string> using namespace std; int main() { string S1(“How are you?”),s2; s2 = “Do you love C++”; s3 = “How are you?”; if (s1 > s2) cout <<“S1 is greater than S2”; if (s1==s3) cout << “S1 is equal to S3”; return 0; } Output: S1 is greater than S2 S1 is equal to S3 Fist, MMU, Melaka

56 Indexing String Individual characters of a string can be accessed by indexing the string, using the [] operator string s(“Hello”); char c = s[2]; // Sets c = ‘l’ This operator returns a reference to the character, allowing us to modify that character within the original string directly s[2] = ‘g’; // Sets s = “Heglo” Drawback :This operator is that it does not check whether the index is valid (i.e. valid range) char c = s[10]; // This is permitted char d = s[-5]; // This is also permitted Thus, the use of the index operator for accessing characters is generally discouraged // Instead Use at( ) function Fist, MMU, Melaka

57 Indexing String Instead, you should use the function at(), which performs the same general operation, but verifies that the index is valid string s(“Hello”); char c = s.at(2); // Sets c = ‘l’ char d = s.at(10); // It won’t like this char e = s.at(-5); // It won’t like this either If the index is invalid, the program will terminate Just as with the index operator, the function at() returns a reference to the character, allowing us to modify it directly s.at(2) = ‘g’; // Sets s = “Heglo” Fist, MMU, Melaka

58 Manipulating String The string class provides a wide variety of ways in which string’s can be combined, decomposed, and otherwise manipulated The length of a string (excluding a null terminator) can be determined using either of two functions: length() and size() string s(“Hello”); cout << s.length() << endl; // Displays ‘5’ cout << s.size() << endl; // Displays ‘5’ empty() - will return a bool that is true if the number of characters in the string is 0 (i.e. length()/size() return 0) and false otherwise string t; bool x = s.empty(); // Sets x = false bool y = t.empty(); // Sets y = true Fist, MMU, Melaka

59 Manipulating String string& insert(size_type pos, const string& s)
Inserts a string into the current string, starting at the specified position and returns a reference to the modified string string s(“hello”); s.insert(3, “goodbye”); // Sets s to “helgoodbyelo” replace(start,size,string) Replaces size number of characters of invoking string object at the start index string s1(“It is a very rainy day.”); string s2(“sunny”); s1.replace (13,6,s2) Fist, MMU, Melaka

60 Manipulating String S1.erase(8, 5); // S1 is “It is a sunny day”
erase(start,size) Erase size number of characters from the invoking string object at the start index string S1(“It is a very sunny day.”; S1.erase(8, 5); // S1 is “It is a sunny day” Append: string& append(size_type pos, const string& s) Appends the specified string into the current string and returns a reference to the modified string string s(“hello”); s.append(“goodbye”); // Sets s to “hellogoodbye” OR string s(“hello”); s += “goodbye”; // Sets s to “hellogoodbye string u, s(“good”) ,s1(“morning”); u = s +s1 // Sets u to good morning Fist, MMU, Melaka

61 Program - Using Editing Functions
#include <iostream> #include <string> using namespace std; int main() { string S1("It is a rainy day."); string S2("very "); string S3("sunny "); cout << "\n S1 = " << S1; cout << "\n S2 = " << S2; cout << "\n S3 = " << S3; S1.insert(8,S2); S1.replace(13, 6, S3); S1.erase(8, 5); cout << "\n S1 = " << S1; S1 = "\nAll done with strings."; cout << S1 << endl; return 0; } Fist, MMU, Melaka

62 Manipulating String Find: The set of find() functions are used to locate substrings or individual characters within a string size_type find(const string& s, size_type pos = 0) const Searches for the string s within the current string, starting at position pos – if successful, returns the index of the first character in the substring string s(“hello”); cout << s.find(“ll”) << endl; // Displays ‘2’ findr(string,start) Returns the index of the string located within the invoking string object searching in reverse order. The search begins at the start index Fist, MMU, Melaka

63 Program - Using Search Functions
#include <iostream> #include <string> using namespace std; int main() { string S1("One potato, two potato, three potato, four."); string S2("potato"); string S3("apples" ); string S4("bananas"); cout << endl << S3; int First_pos, Last_pos; cout << "\n S1 = " << S1; cout << "\n S2 = " << S2; First_pos = S1.find(S2,0); cout << "\n The first \"potato\" is at " << First_pos; Last_pos = S1.rfind(S2,string::npos); cout << "\n The last \"potato\" is at " << Last_pos; S1 = "\nAll done with strings."; cout << S1 << endl; return 0; } Fist, MMU, Melaka

64 Manipulating Strings All of the functions for finding substring indexes are const functions This means that while they can locate a substring, they will not allow you to modify it (however, you can use the result in another function, such as replace()) If the function fails to find the substring, npos is return (an invalid index that, if passed to another function as an index argument, will cause the program to terminate) Fist, MMU, Melaka

65 Manipulating String The function substr() can be used to retrieve a portion of a string string substr(size_type pos, size_type n) const Returns up to n characters from the current string, starting at position pos string s(“hello”); cout << s.substr(2, 2) << endl; // Displays ‘ll’ cout << s.substr(2, 10) << endl; // Displays ‘llo’ This is also a const function, so editing the return value will not affect the original Fist, MMU, Melaka

66 Program - Convert between String and Character String Arrays
#include <iostream> #include <string> using namespace std; int main() { string S1("I like the sea and C, you see."); string S2; char MyArray[50] = "Is C++ really a B-?"; const char *MyOtherArray; cout << "\n The original string and array" << endl; cout << S1 << endl; cout << MyArray << endl; S2.assign(MyArray); MyOtherArray = S1.c_str(); assigns the number of characters from a character string array into the invoking string beginning at the start index Fist, MMU, Melaka

67 Program - Convert between String and Character String Arrays
cout << "\n The converted array and string" << endl; cout << MyOtherArray << endl; cout << S2 << endl; return 0; } C_str function used to convert a string to a const char*. The c_str function returns a pointer to a null terminated string; however you may not change the contents of this string Fist, MMU, Melaka


Download ppt "Files in C++ Week 2 Computer Programming II 1."

Similar presentations


Ads by Google