22
--------------------------------------------------- ----------------------------------------- Notes -- CSC 310 -- 4 --------------------------------------------------- ----------------------------------------- sizeof ( ) operator can be used to return the size, in bytes, of the given expression or type used with the array name, the number of bytes in the whole array is returned. cin.getline() cin.get(ch); // will read any character input into ch. cin.getline(s3, length);// will read any characters input // into string s3, until input is '\n' or // length-1 is reached, then appends '\0' to s3. String a character array with a null symbol (\0) placed immediately after the last character. The length of the longest possible string is one less than the size of the array. int main() { char a[10] = {'y','e','s'}; // NOT a string char s[10] = "yes"; // cstring, s[3] has '\0' from system. char t[4] = "yes"; // cstring, with just enough space } A string can be assigned an initial value when declared. But the assignment is not allowed anywhere else in the program char s1[20]; // uninitialized char s2[10] = "Class 310"; // spaces are allowed char s3[] = "hello"; // if the length is not specified, // compiler automatically determines // the size needed --------------------------------------------------- ----------------------------------------- 1

Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

Embed Size (px)

Citation preview

Page 1: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

sizeof ( ) operator

can be used to return the size, in bytes, of the given expression or typeused with the array name, the number of bytes in the whole array is returned.

cin.getline()

cin.get(ch); // will read any character input into ch.cin.getline(s3, length);// will read any characters input

// into string s3, until input is '\n' or // length-1 is reached, then appends '\0' to s3.

String

a character array with a null symbol (\0) placed immediately after the last character.

The length of the longest possible string is one less than the size of the array.int main(){ char a[10] = {'y','e','s'}; // NOT a string char s[10] = "yes"; // cstring, s[3] has '\0' from system. char t[4] = "yes"; // cstring, with just enough space}

A string can be assigned an initial value when declared. But the assignment

is not allowed anywhere else in the program

char s1[20]; // uninitialized char s2[10] = "Class 310"; // spaces are allowed char s3[] = "hello"; // if the length is not specified, // compiler automatically determines

// the size needed char s4[] = ""; // empty string

Strings can be used for reading and writing

cout << "Enter a name: "; cin >> s3; // OK. white space skipped and then

// assign to s3 till next whitespace. // Null terminator is added at the end. cout << s3; // OK. output s3 until '\0' in string.

Strings are arrays not simple values therefore they cannot use = or == operators

if (s1 == s2) // NO comparison by ==, same as any array // Sometimes compares array address values

...

--------------------------------------------------------------------------------------------1

Page 2: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

-------------------------------------------------------------------------------------------- s1 = s2; // NO assignment by =, same as any array

--------------------------------------------------------------------------------------------2

Page 3: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

Predefined library functions in <cstring>

strcpy(char target[ ], const char source [ ]);

Copies source string to target, stopping at the terminating null character. Returns a pointer to the target string.

strncpy(char target[ ], const char source [ ],size_t limit);

Same as strcpy, except that at most, limit characters are copied.

strcmp(const char s1[ ], const char s2[ ]);

Performs an unsigned comparison of s1 to s2, starting with the first character in each string and continuing with subsequent characters until the corresponding characters differ.

Returns an integer which is 0, if s1 is equal to s2;a negative number when s1 is alphabetically before s2;a positive number if s1 is alphabetically after s2

strncmp(const char s1[ ], const char s2[ ], size_t Limit);

Same as strcmp, but at most appends Limit characters to s1.

strcat(char target[ ], const char source [ ]);

Appends a copy of source to the end of target. Returns a pointer to target.

strncat(char target[ ], const char source [ ], size_t Limit);

Same as strcat but at most, Limit characters are appended followed by the null character. Returns a pointer to target.

strlen(const char source [ ]);

Calculates the length of a string. Returns the number of characters in s, not counting the null terminating character.

strstr(const char s1[ ], const char pattern[ ]);

Scans a string for the first occurrence of a given pattern.Returns a pointer to the element in s1 where s2 begins or is null if the pattern does not occur in s1.

strrstr(const char s1[ ], const char pattern[ ]);

Same as strstr but returns a pointer to the last occurrence ofthe string in s1, if found.

--------------------------------------------------------------------------------------------3

Page 4: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

This program has an execution flaw-- preconditions were not being checked.

#include <cstring>#include <iostream>using namespace std;

int main(){

char s1[3];strcpy(s1, "This copy statement may occur at any time");cout << "The content of s1 is " << s1 << endl;return EXIT_SUCCESS;

}

Fix the following program

#include <cstring>#include <cstdlib>#include <iostream>using namespace std;

int main(){

char s1[] = "When you come to a fork in the road, ";char s2[] = "take it. Yogi Berra";char s3[20];

cout << "\n s1 contains: " << s1 << endl;cout << " s1 can be copied into s3 \n";strcpy(s3, s1); cout << " s3 contains: " << s3 << endl;

strcat(s3, s2); // concatenate s2 to s3cout << " After concatenation, s3 contains: \t"

<< s3 << endl;

return EXIT_SUCCESS;}

--------------------------------------------------------------------------------------------4

Page 5: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

When are two strings equal? strcmp may not give the results wanted

#include <cstring>#include <iostream>using namespace std;

int main(){

char s1[30] = "science ";char s2[30] = "science";

int diff = strcmp(s1, s2);

if (diff == 0) // if 0 difference, strings are the samecout << endl << s1 << " is equal to " << s2 << endl;

else if (diff < 0)cout << endl << s1 << " is less than " << s2 << endl;

elsecout << endl << s1 << " is greater than " << s2 << endl << endl;

return EXIT_SUCCESS;}

Reading into a string by using cin >> may not get all that was input

#include <iostream>using namespace std;

int main(){

char s3[250];

cout << endl << "\nEnter a sentence: ";cin >> s3;cout << "\n You entered: " << s3 << endl;

return EXIT_SUCCESS;}

The this pointer

Each member function has a this pointer which contains the address of the invoking object. To refer to the invoking object as a whole, use the dereference *this.

--------------------------------------------------------------------------------------------5

Page 6: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

Example prototype of a string class ---------------------------------------------------

#ifndef STRING2_H#define STRING2_H#include <iostream>using namespace std;

namespace mystring{

class String{private: char * str; // pointer to string int len; // length of stringpublic: String(const char * s); // constructor String(); // default constructor String(const String & st); ~String(); // destructor int length() const { return len; }

// overloaded operators String & operator=(const String & st); // Assignment operator String & operator=(const char * s); // Assignment operator #2// friend functions friend bool operator>(const String &st1, const String &st2); friend bool operator<(const String &st, const String &st2); friend bool operator==(const String &st, const String &st2); friend ostream & operator<<(ostream & os, const String & st); friend istream & operator>>(istream & is, String & st);};

}#endif

Definition of a string class ---------------------------------------------------

#include <iostream>#include <cstring>#include "string2.h"using namespace std;

namespace mystring{

String::String(const char * s) // make String from C string{ len = strlen(s); str = new char[len + 1];

strcpy(str, s); }

String::String() // default constructor{ len = 0; str = new char[1]; str[0] = '\0'; // default string

--------------------------------------------------------------------------------------------6

Page 7: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------}

String::String(const String & st) // copy constructor{ len = st.len; str = new char[len + 1]; strcpy(str, st.str);}

String::~String() // destructor{ delete [] str; }

// assign a String to a StringString & String::operator=(const String & st){ if (this == &st)

return *this;delete [] str;len = st.len;str = new char[len + 1];strcpy(str, st.str);return *this;

}

// assign a C string to a StringString & String::operator=(const char * s){ delete [] str; len = strlen(s); str = new char[len + 1]; strcpy(str, s); return *this;}

bool operator>(const String &st1, const String &st2){ if (strcmp(st1.str, st2.str) > 0)

return true;else

return false;}

bool operator<(const String &st1, const String &st2){ if (strcmp(st1.str, st2.str) < 0)

return true;else

return false;}

bool operator==(const String &st1, const String &st2){

--------------------------------------------------------------------------------------------7

Page 8: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

-------------------------------------------------------------------------------------------- if (strcmp(st1.str, st2.str) == 0)

return true;else

return false;}

ostream & operator<<(ostream & os, const String & st){ os << st.str; return os;}

istream& operator>>(istream& is, String & st){ char temp[80]; is.get(temp, 80); if (is)

st = temp; while (is && is.get() != '\n') continue; return is;}

} An application program using the string class -------------------------------------

#include <iostream>#include <cstdlib> // (or stdlib.h) for rand(), srand()#include <ctime> // (or time.h) for time()#include "string2.h"using namespace std;using namespace mystring;

const ARSIZE = 10;const MAXLEN = 81;int main(){ String sayings[ARSIZE]; cout << "Enter up to " << ARSIZE << " short sayings <empty line to quit>:\n"; char temp[MAXLEN]; int i; for (i = 0; i < ARSIZE; i++) { cout << i+1 << ": "; cin.get(temp, MAXLEN); while (cin && cin.get() != '\n') continue; if (!cin || temp[0] == '\0') // empty line? break; // i not incremented else sayings[i] = temp; // overloaded assignment } int total = i; // total # of lines read

--------------------------------------------------------------------------------------------8

Page 9: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

-------------------------------------------------------------------------------------------- cout << "Here are your sayings:\n"; for (i = 0; i < total; i++) cout << "\t" << sayings[i] << "\n";

// use pointers to keep track of shortest, alphabetically first & last strings

String * shortest = &sayings[0]; // initialize to first object String * first = &sayings[0];

String * last = &sayings[0];String * longest = &sayings[0];

for (i = 1; i < total; i++) {

// method 1) of referencing a method by pointerif (sayings[i].length() > (*longest).length())

longest = &sayings[i];

// method 2) of referencing a method by pointer else if (sayings[i].length() < shortest->length()) shortest = &sayings[i];

if (sayings[i] < *first) // compare values first = &sayings[i];

else if (sayings[i] > *last)last = &sayings[i];

}

cout << endl; cout << "Shortest saying:\t" << *shortest << endl; cout << "Longest saying: \t" << *longest << endl;

cout << endl; cout << "First alphabetically:\t" << *first << endl;

cout << "Last alphabetically :\t" << *last << endl;

return EXIT_SUCCESS;}

--------------------------------------------------------------------------------------------9

Page 10: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

Header file for String Assignment (modified version of page 188)

#ifndef ASTRING_H#define ASTRING_H#include <cstdlib> // Provides size_t

namespace astring{ class string { public: // CONSTRUCTORS and DESTRUCTOR string(const char str[ ] = ""); // char string input string(const string& source); // copy from similar class

string(const size_t capacity); // reserve empty string class ~string( ); // delete array // MODIFICATION MEMBER FUNCTIONS void operator +=(const string& addend); // concat - same class void operator +=(const char addend[ ]); // concat - char string void operator +=(char addend); // concat - a character void reserve(size_t n); // allocate space string& operator =(const string& source); // copy a string // CONSTANT MEMBER FUNCTIONS size_t length( ) const { return current_length; }

size_t getAllocated( ) const {return allocated; } char operator [ ](size_t position) const;

char* getString( ) const { return a_string; } // FRIEND FUNCTIONS friend std::ostream& operator <<(std::ostream& outs, const string& source); friend bool operator ==(const string& s1, const string& s2); friend bool operator !=(const string& s1, const string& s2); friend bool operator >=(const string& s1, const string& s2); friend bool operator <=(const string& s1, const string& s2); friend bool operator > (const string& s1, const string& s2); friend bool operator < (const string& s1, const string& s2); private: char* a_string; size_t allocated; size_t current_length; };

// NON-MEMBER FUNCTIONS for the string class string operator +(const string& s1, const string& s2); std::istream& operator >>(std::istream& ins, string& target); void getline(std::istream& ins, string& target, char delimiter);}

#endif

--------------------------------------------------------------------------------------------10

Page 11: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

Demo program to exercise String (modified version of page 195)

// FILE: str_demo.cpp// From Chapter 4 of Data Structures and Other Objects (Second Edition)// ________________________________________________________________________//// This file has been modified to work with Microsoft Visual C++ 6.0,// as described in www.cs.colorado.edu/~main/vc6.html// ________________________________________________________________________//// This is a small demonstration program showing how the string class is used.#include <iostream> // Provides cout and cin#include <cstdlib> // Provides EXIT_SUCCESS#include "string.h" // Or use the Standard Library <string>using namespace std;using namespace astring;

// PROTOTYPES for functions used by this demonstration program:void match( const astring::string& variety, const astring::string& mine, const astring::string& yours );// The two strings, mine and yours, are compared. If they are the same, then a // message is printed saying they are the same; otherwise mine is printed// in a message. In either case, the string variety is part of the message.

int main( ){ const astring::string BLANK(" "); astring::string me_first("Demo"), me_last("Program"); astring::string you_first, you_last, you; cout << "What is your first name? "; cin >> you_first; match("first name", me_first, you_first); cout << "What is your last name? "; cin >> you_last; match("last name", me_last, you_last);

you = you_first + BLANK + you_last; cout << "I am happy to meet you, " << you << "." << endl; return EXIT_SUCCESS; }

void match( const astring::string& variety, const astring::string& mine,

--------------------------------------------------------------------------------------------11

Page 12: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

-------------------------------------------------------------------------------------------- const astring::string& yours ){ if (mine == yours) cout << "That is the same as my " << variety << "!" << endl; else cout << "My " << variety << " is " << mine << "." << endl;}

A partially complete string implementation file

#include <iostream>#include <cstring>#include "string.h"using namespace std;

namespace astring{

string::string(const char str[ ] ) // make string from C string{ current_length = strlen(str);

allocated = current_length + 1; a_string = new char[allocated];

strcpy(a_string, str);}

string::string(const size_t capacity){

current_length = 0;allocated = capacity;a_string = new char[allocated];strcpy(a_string, ""); // put in null

}

string::string(const string& source) // copy constructor{ current_length = source.current_length; allocated = current_length + 1;

a_string = new char[allocated]; strcpy(a_string, source.a_string);}

string::~string() // destructor{ delete [] a_string; }

// assign a string to a stringstring& string::operator=(const string& source){ if (this == &source)

return *this;

--------------------------------------------------------------------------------------------12

Page 13: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------delete [] a_string;current_length = source.current_length;a_string = new char[current_length + 1];strcpy(a_string, source.a_string);return *this;

}

void string::reserve(size_t new_capacity) { char *resized_array;

if (new_capacity == allocated) return; // The allocated memory is already the right size.

if (new_capacity < current_length) new_capacity = current_length; // Can't allocate less than needed.

resized_array = new char[new_capacity]; strcpy(resized_array, a_string); delete [ ] a_string; a_string = resized_array; allocated = new_capacity; }

void string::operator +=(const string& addend){ size_t size = current_length + addend.length() + 1;

if (size > allocated)reserve(size);

strcat(a_string,addend.getString());current_length = current_length + addend.length();

}

bool operator>(const string &st1, const string &st2){ if (strcmp(st1.a_string, st2.a_string) > 0)

return true;else

return false;}

bool operator<(const string &st1, const string &st2){ if (strcmp(st1.a_string, st2.a_string) < 0)

return true;else

return false;}

bool operator==(const string &st1, const string &st2){ if (strcmp(st1.a_string, st2.a_string) == 0)

--------------------------------------------------------------------------------------------13

Page 14: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------return true;

else return false;}

ostream & operator<<(ostream & os, const string & st){ os << st.a_string; return os;}

istream & operator>>(istream & is, string & st){ char temp[80]; is.get(temp, 80); if (is)

st = temp;while (is && is.get() != '\n')

continue; return is;}

string operator +(const string& s1, const string& s2){

string combined(s1.length() + s2.length() + 2);

combined += s1;combined += s2;return combined;

}

}

--------------------------------------------------------------------------------------------14

Page 15: Review of C++ Input and Output - DePaul Universitycondor.depaul.edu/jpetlick/extra/310/310n04.doc · Web view// From Chapter 4 of Data Structures and Other Objects (Second Edition)

--------------------------------------------------------------------------------------------Notes -- CSC 310 -- 4

--------------------------------------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////////////////////////////////Assignment 4(a) (10 points)

Programming Project --

Implement the string class. Include the missing functions for logical comparisons and the function +=(char addend)

/////////////////////////////////////////////////////////////////////////////////////////////////////////Assignment 4(b) (15 points)

Programming Project --

In addition to doing 4(a), include the missing function:char operator [ ] (size_t position) const

and add the functions listed for problem 1 page 204://///////////////////////////////////////////////////////////////////////////////////////////////////////

--------------------------------------------------------------------------------------------15