LECTURE 6 cs201 C++ Strings.

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
Starting Out with C++, 3 rd Edition 1 Chapter 12 – File Operations.
CPS120: Introduction to Computer Science Lecture 15 B Data Files.
STARTING OUT WITH STARTING OUT WITH Class 15 Honors.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 19 - Class string and Stream Processing Outline 19.1Introduction 19.2 string Assignment and.
 2006 Pearson Education, Inc. All rights reserved Class string and String Stream Processing.
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Standard Template Library Ming.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
計算機概論實習 How to Use string Template class basic_string String manipulation (copying, searching, etc.) typedef basic_string string; Also typedef.
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
 2006 Pearson Education, Inc. All rights reserved Class string and String Stream Processing.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
String Constructors string str; // creates an empty //string string str(“abc”); // creates a string // from a C-string string str(aString); // creates.
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Starting Out with C++, 3 rd Edition 1 File Operations in C++
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
1 Character Strings (Cstrings) Reference: CS215 textbook pages
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Starting Out with C++, 3 rd Edition 1 Chapter 12 – File Operations.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 15 - Class string and String Stream Processing Outline 15.1 Introduction 15.2 string Assignment.
String Class Mohamed Shehata 1020: Introduction to Programming.
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Learners Support Publications Working with Files.
Lecture 14 Arguments, Classes and Files. Arguments.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Starting Out with C++ 1 Chapter 12: File Operations What is a File? A file is a collection on information, usually stored on some electronic medium. Information.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Strings.
CS212: Object Oriented Analysis and Design
Class string and String Stream Processing: A Deeper Look
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
String class and its objects
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Class string and String Stream Processing
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
C++ Programming Lecture 20 Strings
Today’s Objectives 28-Jun-2006 Announcements
Chapter 15 - Class string and String Stream Processing
character manipulation
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

LECTURE 6 cs201 C++ Strings

Creating String Objects Strings 18 Creating String Objects C-string Array of chars that is null terminated (‘\0’). C++ - string Object whose string type is defined in the <string> file has a large repertoire of functions (e.g. length, replace, etc.) char cs[ ] = “Napoleon”; // C-string string s = “Napoleon”; // C++ - string cout << s << “ has “ << s.length() << “ characters.\n”; s.replace(5, 2,”ia”); //changes s to “Napolian

Creating String Objects C ++ Strings 18 Creating String Objects #include <string> //string initialization string s; //s contains 0 characters string s1( "Hello" ); //s1 contains 5 characters string s2 = “Hello”; //s2 contains 5 characters //implicitly calls the constructor string s3( 8, 'x' ); //s3 contains 8 'x' characters string s4 = s3; //s4 contains 8 'x' characters string s5(s2, 3, 2); //s5 copies a substring of s2; it contains ”lo” string type in the <string> header file. string_characteristics.cpp

C ++ Strings String Objects 18 String Objects The C++ string class also defines a length() function for extracting how many characters are stored in a string. cout << s.length() << endl; Prints 4 for the string s == “Leon” You can also use the subscript operator [ ] to access individual characters: e.g. s[0] = ‘N’ ; //where index: 0 to length-1

C ++ Strings String Objects 18 String Objects C++ strings can be compared using relational operators just like fundamental types: If(s2 < s5) cout << “s2 lexicographically precedes s5 \n”; while(s4==s3) //… 'B' is lexicographically greater than 'A' Sample order: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon” compare.cpp

Comparing strings Overloaded operators s1.compare(s2) ==, !=, <, >, <= and >= returns bool s1.compare(s2) returns positive if s1 is lexicographically greater compares letter by letter 'B' lexicographically greater than 'A‘ ‘a’ lexicographically greater than ‘A‘ ‘a’ lexicographically greater than ‘Z‘ returns negative if less; zero if equal Sample order: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon” s1.compare(start, length, s2, start, length) Compare portions of s1 and s2 s1.compare(start, length, s2) Compare portion of s1 with all of s2 Compare.cpp

C ++ Strings String Objects 18 String Objects You can also concatenate C++ strings using the + and += operators: string s = “ABCD*FG”; string s2 = “Robot”; string s5 = “Soccer”; string s6 = s + “HIJK”; //changes s6 to “ABCD*FGHIJK s2 += s5; //changes s2 to “RobotSoccer”

Concatenation Concatenation s3.append( "pet" ); s3 += "pet"; Both add "pet" to end of s3 s3.append( s1, start, N ); Appends N characters from s1, beginning at index start

Substrings Function substr gets a substring s1.substr( start, N ); gets N characters, beginning with index start returns substring

C ++ Strings 18 String Objects Substring function: substr() s6 = “ABCD*FGHIJK”; s4 = s6.substr(5, 3); //changes s4 to “FGH” s4 gets a substring of s6, starting at index 5 and taking 3 characters

C ++ Strings String Objects erase() and replace() functions: 18 String Objects erase() and replace() functions: s6 = “ABCD*FGHIJK”; s6.erase(4, 2); //changes s6 to “ABCDGHIJK”; s6.replace(5, 2, “xyz”); //changes s6 to “ABCDGxyzJK”; replace 2 characters from s6, starting at index 5, with “xyz”

Replacing Characters in a string s1.erase( start ) Erase from index start to end of string, including start Replace s1.replace( begin, N, s2) begin: index in s1 to start replacing N: number of characters to replace s2: replacement string s1.replace( begin, N, s2, index, num ) index: element in s2 where replacement comes from num: number of elements to use when replacing Replace can overwrite characters others.cpp

Example s1.replace( begin, N, s2, index, num ) begin: index in s1 to start replacing N: number of characters to replace s2: replacement string index: element in s2 where replacement comes from num: number of elements to use when replacing string str = "this is an example string."; string str3="sample phrase"; str.replace(19,6, str3, 7, 6); // "this is an example phrase."

C ++ Strings String Objects find() function 18 String Objects find() function returns the index of the first occurrence of a given substring: string s7 = “Mississippi River basin”; //23 characters cout << s7.find(“si”) << endl; //prints 3 cout << s7.find(“so”) << endl; //prints 23, the length of the string If the find() function fails, it returns the length of the string it was searching. i.e. find() returns 4,294,967,295

Finding Strings and Characters in a string Find functions If found, index returned If not found, string::npos returned Public static constant in class string s1.find( s2 ) s1.rfind( s2 ) Searches right-to-left s1.find_first_of( s2 ) Returns first occurrence of any character in s2 Example: s1.find_first_of( "abcd" ) Returns index of first 'a', 'b', 'c' or 'd' others.cpp

Finding Strings and Characters in a string Find functions s1.find_last_of( s2 ) Finds last occurrence of any character in s2 s1.find_first_not_of( s2 ) Finds first character NOT in s2 s1.find_last_not_of( s2 ) Finds last character NOT in s2 others.cpp

Assignment Assignment s2 = s1; s2.assign(s1); Makes a separate copy s2.assign(s1); Same as s2 = s1; myString.assign(s, start, N); Copies N characters from s, beginning at index start Individual character assignment s2[0] = s3[2];

Range-checking Range-checking s3.at( index ); [] has no range checking Returns character at index Can throw an out_of_range exception [] has no range checking #include <exception> ... string s = "leon"; try{ char letter = s.at( 50 ); cout <<"letter is = " << letter << endl; } catch(exception& e){ cout << "out_of_range exception: " << e.what() << endl; string_characteristics.cpp

Swapping strings s1.swap(s2); Switch contents of two strings

string Characteristics Member functions s1.size() and s1.length() Number of characters in a string s1.capacity() Number of elements that can be stored without reallocation s1.max_size() Maximum possible string size s1.empty() Returns true if empty s1.resize(newlength) Resizes string to newlength string_characteristics.cpp

Inserting Characters into a string s1.insert( index, s2 ) Inserts s2 before position index s1.insert( index, s2, index2, N ); Inserts substring of s2 before position index Substring is N characters, starting at index2 others.cpp

Conversion to C-Style char* Conversion functions Strings are not necessarily null-terminated s1.copy( ptr, N, index ) Copies N characters into the array ptr Starts at location index Need to null terminate char str[8]; string s2 = "cathode"; s2.copy(str, 5, 2); //copy 5 characters into str //starting at index 2 //strcat(str,"\0"); //does not work str[5] = '\0'; //this is required cout << "str = " << str << endl; cout << "s2 = " << s2 << endl; Output: str = thode s2 = cathode

Conversion to C-Style char * Strings Conversion functions s1.c_str() Returns const char * Null terminated e.g. Useful for filenames: ifstream in( s1.c_str() ); s1.data() NOT null-terminated

Warning! No conversion from int or char The following definitions could return errors, or warnings only, but then would cause the program to crash afterwards string error1 = 'c'; string error2( 'u' ); string error3 = 22; string error4( 8 ); However, it can be assigned one char after its declaration: s = 'n';

Output String Stream ostringstream oss; int n = 44; float x = 3.14; oss << "Hello!\t" << n << '\t' << x; string s = oss.str(); cout << endl << s << endl; Serves as a conduit to an anonymous string which can be read with the built-in oss.str() function that is bound to the oss object Remember sprintf()?, how does it compare to this one? output_string_stream.cpp

Input String Stream iss is defined and bound to buffer const string buffer = oss.str(); istringstream iss(buffer); string word; int m; float y; iss >> word >> m >> y; s = iss.str(); cout << endl << s << endl; cout << "word = " << word << endl; cout << "m = " << m << endl; cout << "y = " << y << endl; iss is defined and bound to buffer Contents of buffer can be accessed as elements of a string, or by formatted input through the iss object. Remember sscanf()?, how does it compare to this one? input_string_stream.cpp All extractions from iss will come from the contents of buffer, as if it were an external file.

Using string example Input file: Example Output: #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <sstream> using namespace std; int main(){ string s1("mydata.txt"); ifstream in( s1.c_str() ); char buffer[1024]; while( in.getline( buffer, 1024 ) ){ string stemp( buffer ); cout << "Line is:" << stemp << endl; if( stemp[0] != '#' ){ stringstream stris( stemp ); double d1, d2; stris >> d1 >> d2; cout << d1 << "," << d2 << endl; } cout << endl; in.close(); return 0; Using string example Input file: 1.0 2.0 1.1 2.4 1.8 2.8 #1.34 2.99 1.4 8.99 Example Output: Line is:1.0 2.0 1,2 Line is:1.1 2.4 1.1,2.4 Line is:1.8 2.8 1.8,2.8 Line is:#1.34 2.99 Line is:1.4 8.99 1.4,8.99 (or could use strtok, C String tokenizers)

Alternatively: (no C-style char*) #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <sstream> using namespace std; int main(){ string s1("mydata.txt"); ifstream in( s1.c_str() ); char buffer[1024]; while( in.getline( buffer, 1024 ) ){ string stemp( buffer ); cout << "Line is:" << stemp << endl; if( stemp[0] != '#' ){ stringstream stris( stemp ); double d1, d2; stris >> d1 >> d2; cout << d1 << "," << d2 << endl; } cout << endl; in.close(); return 0; Alternatively: (no C-style char*) int main(){ string s1("mydata.txt"); ifstream in( s1.c_str() ); string buffer; while(getline( in, buffer ) ){ cout << "Line is:" << buffer << endl; if( buffer[0] != '#' ){ istringstream stris( buffer ); double d1, d2; stris >> d1 >> d2; cout << "data: " << d1 << "," << d2 << endl; } cout << endl; in.close(); return 0; File_stringstream2.cpp

Returns an iterator to the start of the string. *c_str(); Method Use append(char *pt); append(char *pt, size_t count); append(string &str, size_t offset,size_t count); append(string &str); append(size_t count, char ch); append(InputIterator Start, InputIterator End); Appends characters to a string from C-style strings, char's or other string objects. at(size_t offset); Returns a reference to the character at the specified position. Differs from the subscript operator, [], in that bounds are checked. begin(); Returns an iterator to the start of the string. *c_str(); Returns a pointer to C-style string version of the contents of the string. clear(); Erases the entire string. copy(char *cstring, size_t count, size_t offset); Copies "count" characters into a C-style string starting at offset. empty(); Test whether a string is empty. end(); Returns an iterator to one past the end of the string. erase(iterator first, iterator last); erase(iterator it); erase(size_t pos, size_t count); Erases characters from the specified positions. • C-Style Character Arrays • String Class • String Operations • String Class Methods • Using String Methods    More of this Feature

Method Use find(char ch,size_t offset = 0); find(char *pt,size_t offset = 0); find(string &str,size_t offset = 0); Returns the index of the first character of the substring when found. Otherwise, the special value "npos" is returned. find_first_not_of(); Same sets of arguments as find. Finds the index of the first character that is not in the search string. find_first_of(); Same sets of arguments as find. Finds the index of the first character that is in the search string. find_last_not_of(); Same sets of arguments as find. Finds the index of the last character that is not in the search string. find_last_of(); Same sets of arguments as find. Finds the index of the last character that is in the search string. insert(size_t pos, char *ptr); insert(size_t pos, string &str); insert(size_t pos, size_t count, char ch); insert(iterator it, InputIterator start, InputIterator end); Inserts characters at the specified position. push_back(char ch); Inserts a character at the end of the string. replace(size_t pos, size_t count, char *pt); replace(size_t pos, size_t count, string &str); replace(iterator first, iterator last, char *pt); replace(iterator first, iterator last, string &str); Replaces elements in a string with the specified characters. The range can be specified by a start position and a number of elements to replace, or by using iterators. size(); Returns the number of elements in a string. swap(string &str); Swaps two strings.

Exercise Write a program to accept string and then count the vowels and reverses it. Vowels are {a, e, i, o, u, A, E, I, O, U}

Example Write a program that print the number of occurrences of a given character c in a given string s.

File

What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.

File Stream Objects Use of files requires file stream objects There are three types of file stream objects (1) ifstream objects: used for input (2) ofstream objects: used for output (3) fstream objects: used for both input and output

Opening a File for Input Create an ifstream object in your program ifstream inFile; Open the file by passing its name to the stream’s open member function inFile.open("myfile.dat");

Opening a File for Output Create an ofstream object in your program ofstream outFile; Open the file by passing its name to the stream’s open member function outFile.open("myfile.dat");

The fstream Object fstream object can be used for either input or output fstream file; To use fstream for input, specify ios::in as the second argument to open file.open("myfile.dat",ios::in); To use fstream for output, specify ios::out as the second argument to open file.open("myfile.dat",ios::out);

#include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; // Declare file stream object char fileName[81]; cout << "Enter the name of a file you wish to open\n"; cout << "or create: "; cin.getline(fileName, 81); dataFile.open(fileName, ios::out); cout << "The file " << fileName << " was opened.\n"; }

File Mode Flags ios::app create new file, or append to end of existing file ios::ate go to end of existing file; write anywhere ios::binary read/write in binary mode (not text mode) ios::in open for input ios::out open for output See See pr13-02.cpp

Program // This program demonstrates the opening of a file at the // time the file stream object is declared. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("names.dat", ios::in | ios::out); cout << "The file names.dat was opened.\n"; }

Testing for Open Errors dataFile.open(“cust.dat”, ios::in); if (!dataFile) { cout << “Error opening file.\n”; }

Another way to Test for Open Errors dataFile.open(“cust.dat”, ios::in); if (dataFile.fail()) { cout << “Error opening file.\n”; }

// This program demonstrates the close function. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; dataFile.open("testfile.txt", ios::out); if (!dataFile) cout << "File open error!" << endl; return; } cout << "File was created successfully.\n"; cout << "Now closing the file.\n"; dataFile.close();

Using << to Write Information to a File The stream insertion operator (<<) may be used to write information to a file. outputFile << “I love C++ programming !”

// This program writes information to a file, closes the file, // then reopens it and appends more information. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; dataFile.open("demofile.txt", ios::out); dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile.close(); dataFile.open("demofile.txt", ios::app); dataFile << "Willis\n"; dataFile << "Davis\n"; }

Using >> to Read Information from a File The stream extraction operator (>>) may be used to read information from a file.

Program continues for (int count = 0; count < 4; count++) { dataFile >> name; cout << name << endl; } dataFile.close(); cout << "\nDone.\n";

Detecting the End of a File The eof() member function reports when the end of a file has been encountered. if (inFile.eof()) inFile.close();

The getline Member Function dataFile.getline(str, 81, ‘\n’); str – This is the name of a character array, or a pointer to a section of memory. The information read from the file will be stored here. 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. ‘\n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left our, ‘\n’ is the default.)

The get Member Function inFile.get(ch);

Program // This program asks the user for a file name. The file is // opened and its contents are displayed on the screen. #include <iostream.h> #include <fstream.h> void main(void) { fstream file; char ch, fileName[51]; cout << "Enter a file name: "; cin >> fileName; file.open(fileName, ios::in); if (!file) cout << fileName << “ could not be opened.\n"; return; }

file.get(ch); // Get a character while (!file.eof()) { Program continues file.get(ch); // Get a character while (!file.eof()) { cout << ch; file.get(ch); // Get another character } file.close();

The put Member Function outFile.put(ch);

Program // This program demonstrates the put member function. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("sentence.txt", ios::out); char ch; cout << "Type a sentence and be sure to end it with a "; cout << "period.\n"; while (1) { cin.get(ch); dataFile.put(ch); if (ch == '.') break; } dataFile.close();

Binary Files Binary files contain data that is unformatted, and not necessarily stored as ASCII text. file.open(“stuff.dat”, ios::out | ios::binary);

Program // This program uses the write and read functions. #include <iostream.h> #include <fstream.h> void main(void) { fstream file(“NUMS.DAT", ios::out | ios::binary); int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "Now writing the data to the file.\n"; file.write((char*)buffer, sizeof(buffer)); file.close(); file.open("NUMS.DAT", ios::in); // Reopen the file. cout << "Now reading the data back into memory.\n"; file.read((char*)buffer, sizeof(buffer)); for (int count = 0; count < 10; count++) cout << buffer[count] << " "; }

Program // This program demonstrates the use of a structure variable to // store a record of information to a file. #include <iostream.h> #include <fstream.h> #include <ctype.h> // for toupper // Declare a structure for the record. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; };

Program continues void main(void) { fstream people("people.dat", ios::out | ios::binary); Info person; char again; if (!people) cout << "Error opening file. Program aborting.\n"; return; } do cout << "Enter the following information about a ” << "person:\n"; cout << "Name: ";

Program continues cin.getline(person.name, 51); cout << "Age: "; cin >> person.age; cin.ignore(); // skip over remaining newline. cout << "Address line 1: "; cin.getline(person.address1, 51); cout << "Address line 2: "; cin.getline(person.address2, 51); cout << "Phone: "; cin.getline(person.phone, 14); people.write((char *)&person, sizeof(person)); cout << "Do you want to enter another record? "; cin >> again; cin.ignore(); } while (toupper(again) == 'Y'); people.close(); }