410 likes | 428 Views
Explore the concepts of strings, I/O streams, and data types in C++. Understand string operations and file handling techniques for efficient programming.
E N D
Cairo University, Faculty of Computers and Information CS213 – 2018 / 2019Programming IILecture 3: C++ Primer – Part 3 By Dr. Mohamed El-Ramly
Lecture Objective / Content • Strings • I/O Streams
simple structured integral enum array struct union class floating char short int long bool address float double long double pointer reference C++ Data Types
Strings • Strings are one of the most important and frequently used data types. • A string is just a sequence of characters. • String "hello, world" is a sequence of 12 characters • C++ supports C-style strings and a string data type and its operations in <string> interface.
Strings • A data type is defined by two properties: • a domain and a set of operations. • What is the domain of type string? • What are the operations that apply to string? • C++ standard introduced the string type that presents an abstract view of string and a richer set of facilities for operating on strings.
Operations on the string type • initialize a string variable is with a string literal: • string str = "Hello"; • String concatenation with + operator: • string str2 = str + "World"; • The addition operator is overloaded, • string str = "Stanford"; • str += '!';
Operations on the string type • Operations on strings were defined to mimic the behavior of those operations on the built-in primitive types. • str2 = str1; • This assignment overwrites any previous contents of str2 • The variables str1 and str2 remain independent.
Operations on string Type • When passing a string as parameter, a copy is made. Changes to the parameter made within a function are not reflected in the calling function. • Strings can be compared lexicographically using the relational operators, ==, !=, <, >, <=, and >=. • if (str == "quit") ... • "abc" is not equal to "ABC".
Operations on string Type • int numChars = str.length(); • length() is method or member function, defined in lass string. • Free functions are functions that do not belong to a class.
Operations on string Type • To access the ith character from a string str using the notation like that of array selection, as follows: str[i] • Index numbers in a string begin at 0 to str.length()-1
Operations on string Type • The standard idiom for processing every character in a string looks like this: • for (int i = 0; i < str.length(); i++) { . . body of loop that manipulates str[i] . . . • } • str[i] is the ith character in the string. • The loop continues until i reaches the length of the string.
Operations on string Type • Thus, you can count the number of spaces in a string using the following function: • int CountSpaces(string str) { int nSpaces = 0; for (int i=0;i<str.length(); i++) if (str[i] == ' ') nSpaces++; return nSpaces; • }
C-Style Strings • string class is C++ choice for string manipulation. string is a class that has member functions and attributes. • C-style string are still supported. These are arrays of char ending with null character (ASCII 0)
C-Style Strings • No explicit way to know the C-style string length. Functions exist to manipulate C strings.
Standard I/O and file streams • The most commonly used library is the I/O stream library, iostream in order to display output using the coutstream. • fstream extends iostream with additional features that make it possible to read and write files. • cin, cout, cerr
Data Files • Text files • Ordinary text in ASCII format • Lines end with ‘\n’ • File ends with EOF • Binary files • Data in binary format • Number 13 is stored as • 00000000-00000000-00000000-00001101
Using File Streams • Declare a stream variable • #include <fstream> • ifstreaminfile; • ofstreamoutfile; • Open the file • infile.open("myfile.txt"); • string str ="myfile.txt"; • infile.open(str.c_str());//mustcallc_str
Data Files • Open the file • if (infile.fail()) ………… // Test file first • infile.clear (); • Read data • Character by chatracter • Line by line • Formatted data • Close file • infile.close();
Formatted Stream Input and Output • outfile << "text " << num <<endl; • Use I/O manipulators as needed • int num; • infile >> num; • How can I read all content in file
Formatted Stream Input and Output • What happens, if I attempt • int num1, num2; • string str; • char ch; • infile >> num1 >> num2 >> str >> ch;
Looping Through a File int total, num; total = 0; while (true) { infile >> num; if (infile.fail()) break; total += num; }
Single Character I/O • int get(); // returns int not char • outfile.put(ch); • void CopyFile(ifstream & infile, ofstream & outfile) { int ch; while ((ch = infile.get()) != EOF) outfile.put(ch); • } • infile.unget(); // return back last char
Line Oriented I/O • getline(infile, str);
Other ANSI C++ Libraries • string, fstream, iostream, iomanip • cmath, cctype
حكمة اليوم • الوسادة تحمل رأس الغني والفقير و الصغير والكبيروالغفير والامير، ولكن لا ينام بعمق إلا مرتاح الضمير. • لا تترك صلاتك أبدا فهناك الملايين تحت القبور يتمنون لو تعود بهم الحياة ليسجدوا ولو سجدة.
Readings of Week 1 • Chapters 1, 2, 3, 4, 11 • You must read and try the examples in these chapters. • Solve the exercises at chapters’ ends.