Prompt functions
see page 767-768 for many prompt functions
- #include "prompt.h"
string PromptString(const string & prompt)
// post: returns string entered by user
{
string word;
cout << prompt;
cin >> word;
return word;
}
bool PromptYesNo(string prompt)
// postcondition: returns true iff user enters yes
{
string str;
char ch;
do
{
cout << prompt << " ";
cin >> str;
ch = tolower(str[0]);
} while (ch != 'y' && ch != 'n');
return ch == 'y';
}
Input File Streams
Declaring a file stream to read from instead of cin
-
#include ;
- declare an ifstream variable
ifstream readin;
- open filestream bounding it to a file
string file = "words";
readin.open(file.c_str());
- use your variable instead of cin to read
string word;
readin >> word;
- close file stream when done
readin.close();
Can create an output stream to write to instead of cout
First part of Today's Classwork
Iterator class
programing pattern (Iteration) you will see over and over
process all the "entries" in the class
Example: StringSetIterator - process all the words in a set
Algorithm
- create iterator
- position at first word
- while (current entry is valid)
- process current entry
- move to next entry
Set Class for strings
set - collection of items with no duplicates
class StringSet
{
public:
StringSet();
StringSet(int isize); // initialize size -- for efficiency
// accessors
bool contains(const string& s) const; // true if s in the set
int size() const; // returns number of items in set
// mutators
void insert(const string& s); // inserts s in set
void erase (const string& s); // removes s from set
void clear(); // removes all items from set
private:
// not shown
};
class StringSetIterator
{
public:
StringSetIterator(const StringSet& s);
void Init() const;
bool HasMore() const;
void Next() const;
string Current() const;
private:
// not shown
};
Example
Note: even though the StringSet changes, the iterator uses the changed
StringSet
#include
#include
using namespace std;
#include "utils.h"
#include "stringset.h"
int main()
{
StringSet A;
A.insert("sad");
A.insert("fun");
A.insert("sad");
A.insert("tickle");
A.insert("sad");
StringSetIterator T(A);
for (T.Init(); T.HasMore(); T.Next())
{
cout << T.Current() << endl;
}
cout << endl;
A.erase("sad");
for (T.Init(); T.HasMore(); T.Next())
{
cout << T.Current() << endl;
}
cout << endl;
A.clear();
for (T.Init(); T.HasMore(); T.Next())
{
cout << T.Current() << endl;
}
cout << endl;
WaitForReturn();
return 0;
}
What is output?
Second Part of Today's Classwork
Susan H. Rodger
Last modified: Wed Oct 15 12:24:15 EDT 2003