while (!in1.eof()) // while not at the end of the file
{
// read and process some input from the file
}
char letter = 'A'; cout << letter;
ostream& put(char c);Sample calls:
char ch1 = 'A', ch2 = 'B', ch3 = 'C'; cout.put(ch1); // equivalent to: cout << ch1; cout.put(ch2); // equivalent to: cout << ch2;Since it returns type ostream&, it can be cascaded, like the insertion operator:
cout.put(ch1).put(ch2).put(ch3);
char letter; cin >> letter;
int peek(); // returns next char, doesn't extract int get(); // extracts one char from input, returns ascii value istream& get(char& ch); // extracts one char from input, stores in ch
char ch1, ch2, ch3;
cin >> ch1 >> ch2 >> ch3; // reads three characters, skipping white space
// no parameter version of get -- no white space skipped
ch1 = cin.get();
ch2 = cin.get();
ch3 = cin.get();
// Single-parameter version of get, which can also be cascaded
cin.get(ch1).get(ch2).get(ch3);
// example of peek() -- trying to read a digit, as a char
char temp = cin.peek(); // look at next character
if (temp < '0' || temp > '9')
cout << "Not a digit";
else
ch1 = cin.get(); // read the digit
cin.ignore(); // skip the next 1 character of input cin.ignore(30); // skip the next 30 characters of input cin.ignore(100,'\n'); // skip to the next newline, up to 100 characters maximum // i.e. skip no more than 100
if (cin.fail())
// then do something to handle the error
Here's a quick description of some of the useful functions. See the
chart on page 247 of the textbook for more details and examples.
All of these functions take a single character as a parameter --
assume that ch is a char:
void Show()
{
cout << "Hello, World\n";
}
A call to this function always prints to standard output
(cout)
Show();
void Show(ostream& output)
{
output << "Hello, World\n";
}
Notice that I can do the printing to different output destinations now:
Show(cout); // prints to standard output stream Show(cerr); // prints to standard error stream
void PrintRecord(ofstream& fout, int acctID, double balance)
{
fout << acctID << balance << '\n';
}
Now I could call this function to print the same data format to different
files:
ofstream out1, out2;
out1.open("file1.txt");
out2.open("file2.txt");
PrintRecord(out1, 123, 45.67); // prints to file1.txt
PrintRecord(out1, 124, 67.89); // prints to file1.txt
PrintRecord(out2, 1000, 123.09); // prints to file2.txt
PrintRecord(out2, 1001, 2087.64); // prints to file2.txt
// prototypes
void PrintRecord(ofstream& fout, int id, double bal);
void PrintRecord2(ostream& out, int id, double bal);
// calls
ofstream out1;
out1.open("file.txt");
PrintRecord(out1, 12, 34.56); // legal
PrintRecord(cout, 12, 34.56); // NOT legal (attempt to pass parent into child type)
PrintRecord2(out1, 12, 34.56); // legal
PrintRecord2(cout, 12, 34.56); // legal (pass child into parent)