Input, Output, and Files |
|---|
// write.cpp -- use cout.write()
#include <iostream.h>
#include <string.h>
int main(void)
{
char * state1 = "Ohio";
char * state2 = "Utah";
char * state3 = "Euphoria";
int len = strlen(state2);
cout << "Increasing loop index:\n";
for (int i = 1; i <= len; i++)
{
cout.write(state2,i);
cout << "\n";
}
// concatenate output
cout << "Decreasing loop index:\n";
for (i = len; i > 0; i--)
cout.write(state2,i) << "\n";
// exceed string length
cout << "Exceeding string length:\n";
cout.write(state2, len + 5) << "\n";
return 0;
}
// defaults.cpp -- cout default formats
#include <iostream.h>
int main(void)
{
cout << "12345678901234567890\n";
char ch = 'K';
int t = 273;
cout << ch << ":\n";
cout << t << ":\n";
cout << -t <<":\n";
double f1 = 1.200;
cout << f1 << ":\n";
cout << (f1 + 1.0 / 9.0) << ":\n";
double f2 = 1.67E2;
cout << f2 << ":\n";
f2 += 1.0 / 9.0;
cout << f2 << ":\n";
cout << (f2 * 1.0e4) << ":\n";
double f3 = 2.3e-4;
cout << f3 << ":\n";
cout << f3 / 10 << ":\n";
return 0;
}
// manip.cpp -- using format manipulators
#include <iostream.h>
int main(void)
{
cout << "Enter an integer: ";
int n;
cin >> n;
cout << "n n*n\n";
cout << n << " " << n * n << " (decimal)\n";
// set to hex mode
cout << hex;
cout << n << " ";
cout << n * n << " (hexadecimal)\n";
// set to octal mode
cout << oct << n << " " << n * n << " (octal)\n";
// alternative way to call a manipulator
dec(cout);
cout << n << " " << n * n << " (decimal)\n";
return 0;
}
// width.cpp -- use the width method
#include <iostream.h>
int main(void)
{
int w = cout.width(30);
cout << "default field width = " << w << ":\n";
cout.width(5);
cout << "N" <<':';
cout.width(8);
cout << "N * N" << ":\n";
for (long i = 1; i <= 100; i *= 10)
{
cout.width(5);
cout << i <<':';
cout.width(8);
cout << i * i << ":\n";
}
return 0;
}
// fill.cpp -- change fill character for fields
#include <iostream.h>
int main(void)
{
cout.fill('*');
char * staff[2] = { "Waldo Whipsnade", "Wilmarie Wooper"};
long bonus[2] = {900, 1350};
for (int i = 0; i < 2; i++)
{
cout << staff[i] << ": $";
cout.width(7);
cout << bonus[i] << "\n";
}
return 0;
}
// precise.cpp -- set the precision
#include <iostream.h>
int main(void)
{
float price1 = 20.40;
float price2 = 1.9 + 8.0 / 9.0;
cout << "\"Furry Friends\" is $" << price1 << ".\n";
cout << "\"Fiery Fiends\" is $" << price2 << ".\n";
cout.precision(2);
cout << "\"Furry Friends\" is $" << price1 << ".\n";
cout << "\"Fiery Fiends\" is $" << price2 << ".\n";
return 0;
}
// showpt.cpp -- set the precision, show trailing point
#include <iostream.h>
int main(void)
{
float price1 = 20.40;
float price2 = 1.9 + 8.0 / 9.0;
cout.setf(ios::showpoint);
cout << "\"Furry Friends\" is $" << price1 << ".\n";
cout << "\"Fiery Fiends\" is $" << price2 << ".\n";
cout.precision(2);
cout << "\"Furry Friends\" is $" << price1 << ".\n";
cout << "\"Fiery Fiends\" is $" << price2 << ".\n";
return 0;
}
// setf.cpp -- use setf() to control formatting
#include <iostream.h>
int main(void)
{
int temperature = 63;
cout << "Today's water temperature: ";
cout.setf(ios::showpos); // show plus sign
cout << temperature << "\n";
cout << "For our programming friends, that's\n";
cout << hex << temperature << "\n"; // use hex
cout.setf(ios::uppercase); // use uppercase in hex
cout.setf(ios::showbase); // use 0X prefix for hex
cout << "or\n";
cout << temperature << "\n";
return 0;
}
// setf2.cpp -- use setf() with 2 arguments to control formatting
#include <iostream.h>
#include <math.h>
int main(void)
{
// use left justification, show the plus sign, show trailing
// zeros, with a precision of 3
cout.setf(ios::left, ios::adjustfield);
cout.setf(ios::showpos);
cout.setf(ios::showpoint);
cout.precision(3);
// use e-notation and save old format setting
long old = cout.setf(ios::scientific, ios::floatfield);
cout << "Left Justification:\n";
for (long n = 1; n <= 41; n+= 10)
{
cout.width(4);
cout << n << "|";
cout.width(12);
cout << sqrt(n) << "|\n";
}
// change to internal justification
cout.setf(ios::internal, ios::adjustfield);
// restore default floating-point display style
cout.setf(old, ios::floatfield);
cout << "Internal Justification:\n";
for (n = 1; n <= 41; n+= 10)
{
cout.width(4);
cout << n << "|";
cout.width(12);
cout << sqrt(n) << "|\n";
}
// use right justification, fixed notation
cout.setf(ios::right, ios::adjustfield);
cout.setf(ios::fixed, ios::floatfield);
cout << "Right Justification:\n";
for (n = 1; n <= 41; n+= 10)
{
cout.width(4);
cout << n << "|";
cout.width(12);
cout << sqrt(n) << "|\n";
}
return 0;
}
// iomanip.cpp -- use manipulators from iomanip.h
// some systems require explicitly linking the math library
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
int main(void)
{
cout.setf(ios::showpoint);
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::right, ios::adjustfield);
cout << setw(6) << "N" << setw(14) << "square root"
<< setw(15) << "fourth root\n";
double root;
for (int n = 10; n <=100; n += 10)
{
root = sqrt(n);
cout << setw(6) << n
<< setw(12) << setprecision(3) << root
<< setw(14) << setprecision(4) << sqrt(root)
<< "\n";
}
return 0;
}
// check_it.cpp -- validate input
#include <iostream.h>
int main(void)
{
cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed, ios::floatfield);
cout << "Enter numbers: ";
double sum = 0.0;
double input;
while (cin >> input)
{
sum += input;
}
cout << "Last value entered = " << input << "\n";
cout << "Sum = " << sum << "\n";
return 0;
}
// get_fun.cpp -- using get() and getline()
// note: some C++ inplementations don't support getline ()
#include <iostream.h>
const int Limit = 80;
int main(void)
{
char input[Limit];
cout << "Enter a string for getline() processing:\n";
cin.getline(input, Limit, '#');
cout << "Here is your input:\n";
cout << input << "\nDone with phase 1\n";
char ch;
cin.get(ch);
cout << "The next input character is " << ch << "\n";
if (ch != '\n')
cin.ignore(Limit, '\n'); // discard rest of line
cout << "Enter a string for get() processing:\n";
cin.get(input, Limit, '#');
cout << "Here is your input:\n";
cout << input << "\nDone with phase 2\n";
cin.get(ch);
cout << "The next input character is " << ch << "\n";
return 0;
}
// peeker.cpp -- some istream methods
#include <iostream.h>
#include <stdlib.h> // for exit()
int main(void)
{
// read and echo input up to a # character
char ch;
while(cin.get(ch)) // terminates on EOF
{
if (ch != '#')
cout << ch;
else
{
cin.putback(ch); // reinsert character
break;
}
}
if (!cout.eof())
{
cin.get(ch);
cout << '\n' << ch << " is next input character.\n";
}
else
{
cout << "End of file reached.\n";
exit(0);
}
while(cin.peek() != '#') // look ahead
{
cin.get(ch);
cout << ch;
}
cin.get(ch);
cout << '\n' << ch << " is next input character.\n";
return 0;
}
// truncate.cpp -- use get() to truncate input line, if necessary
#include <iostream.h>
const int SLEN = 10;
int main(void)
{
char name[SLEN];
char title[SLEN];
cout << "Enter your name: ";
cin.get(name,SLEN);
if (cin.peek() != '\n')
cout << "Sorry, we only have enough room for "
<< name << endl;
while (cin.get() != '\n')
continue;
cout << "Dear " << name << ", enter your title: \n";
cin.get(title,SLEN);
cout << " Name: " << name
<< "\nTitle: " << title << endl;
return 0;
}
// file.cpp -- save to a file
#include <iostream.h> // not needed for many systems
#include <fstream.h>
int main(void)
{
char filename[20];
cout << "Enter name for new file: ";
cin >> filename;
// create output stream object for new file and call it fout
ofstream fout(filename);
fout << "For your eyes only!\n"; // write to file
cout << "Enter your secret number: "; // write to screen
float secret;
cin >> secret;
fout << "Your secret number is " << secret << "\n";
fout.close(); // close file
// create input stream object for new file and call it fin
ifstream fin(filename);
cout << "Here are the contents of " << filename << ":\n";
char ch;
while (fin.get(ch)) // read character from file and
cout << ch; // write it to screen
cout << "Done\n";
return 0;
}
// count.cpp -- count characters in a list of files
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h> // for exit()
// #include <console.h> // for Macintosh
int main(int argc, char * argv[])
{
// argc = ccommand(&argv); // for Macintosh
if (argc == 1) // quit if no arguments
{
cerr << "Usage: " << argv[0] << " filename[s]\n";
exit(1);
}
ifstream fin; // open stream
long count;
long total = 0;
char ch;
for (int file = 1; file < argc; file++)
{
fin.open(argv[file]); // connect stream to argv[file]
count = 0;
while (fin.get(ch))
count++;
cout << count << " characters in " << argv[file] << "\n";
total += count;
fin.close(); // disconnect file
}
cout << total << " characters in all files\n";
return 0;
}
// append.cpp -- append information to a file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h> // for exit()
const char * file = "guests1.dat";
const int Len = 40;
int main(void)
{
char ch;
// show initial contents
ifstream fin;
fin.open(file);
// fin.open(file, ios::in |ios::nocreate); //Symantec, MS VC
if (fin.good()) // or if (fin)
{
cout << "Here are the current contents of the "
<< file << " file:\n";
while ((ios &)fin.get(ch))
cout << ch;
}
fin.close();
// add new names
ofstrea fout(file, ios::out | ios::app);
if (!fout.good()) // or if (!fin)
{
cerr << "Can't open " << file << " file for output.\n";
exit(1);
}
cout << "Enter guest names (enter a blank line to quit):\n";
char name[Len];
cin.getline(name, Len);
while (name[0] != '\0')
{
fout << name << "\n";
cin.getline(name, Len);
}
fout.close();
// show revised file
fin.clear(); // not necessary for some compilers
fin.open(file);
if (fin.good())
{
cout << "Here are the new contents of the "
<< file << " file:\n";
while ((ios &)fin.get(ch))
cout << ch;
}
fin.close();
return 0;
}
// binary.cpp -- append information to a binary file
#include <iostream.h> // not required by most systems
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h> // for exit()
struct planet
{
char name[20]; // name of planet
double population; // its population
double g; // its acceleration of gravity
};
const char * file = "planets.dat";
int main(void)
{
planet pl;
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::right, ios::adjustfield);
// show initial contents
ifstream fin;
fin.open(file, ios::in |ios::binary); // binary file
//NOTE: some systems don't accept the ios::binary mode
if (fin.good())
{
cout << "Here are the current contents of the "
<< file << " file:\n";
while (fin.read((char *) &pl, sizeof pl))
{
cout << setw(20) << pl.name << ": "
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << "\n";
}
}
fin.close();
// add new data
ofstream fout(file, ios::out | ios::app | ios::binary);
//NOTE: some systems don't accept the ios::binary mode
if (fout.fail())
{
cerr << "Can't open " << file << " file for output:\n";
exit(1);
}
cout << "Enter planet name (enter a blank line to quit):\n";
cin.getline(pl.name, 20);
while (pl.name[0] != '\0')
{
cout << "Enter planetary population: ";
cin >> pl.population;
cout << "Enter planet's acceleration of gravity: ";
cin >> pl.g;
while (cin.get() != '\n')
continue;
fout.write((char *) &pl, sizeof pl);
cout << "Enter planet name (enter a blank line "
"to quit):\n";
cin.getline(pl.name, 20);
}
fout.close();
// show revised file
fin.clear(); // not required for some implementations, but won't hurt
fin.open(file, ios::in | ios::binary);
if (fin.good())
{
cout << "Here are the new contents of the "
<< file << " file:\n";
while (fin.read((char *) &pl, sizeof pl))
{
cout << setw(20) << pl.name << ": "
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << "\n";
}
}
fin.close();
return 0;
}
// random.cpp -- random access to a binary file
#include <iostream.h> // not required by most systems
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h> // for exit()
struct planet
{
char name[20]; // name of planet
double population; // its population
double g; // its acceleration of gravity
};
const char * file = "planets.dat";
int main(void)
{
planet pl;
cout.setf(ios::fixed, ios::floatfield);
// show initial contents
fstream finout; // read and write streams
finout.open(file,ios::in | ios::out | ios::ate |
ios::binary);
//NOTE: Some UNIX systems require omitting | ios::binary
int ct = 0;
if (finout.good())
{
finout.seekg(0); // go to beginning
cout << "Here are the current contents of the "
<< file << " file:\n";
while (finout.read((char *) &pl, sizeof pl))
{
cout << ct++ << ": " << setw(20) << pl.name << ": "
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << "\n";
}
if (finout.eof())
finout.clear(); // clear eof flag
else
{
cerr << "Error in reading " << file << ".\n";
exit(1);
}
}
else
{
cerr << file << " could not be opened -- bye.\n";
exit(2);
}
// change a record
cout << "Enter the record number you wish to change: ";
long rec;
cin >> rec;
while (cin.get() != '\n')
continue; // get rid of newline
if (rec < 0 || rec >= ct)
{
cerr << "Invalid record number -- bye\n";
exit(3);
}
streampos place = rec * sizeof pl; // convert to streampos type
finout.seekg(place);
if (finout.fail())
{
cerr << "Error on attempted seek\n";
exit(4);
}
finout.read((char *) &pl, sizeof pl);
cout << "Your selection:\n";
cout << rec << ": " << setw(20) << pl.name << ": "
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << "\n";
if (finout.eof())
finout.clear(); // clear eof flag
finout.seekp(place); // go back
cout << "Enter planet name: ";
cin.getline(pl.name, 20);
cout << "Enter planetary population: ";
cin >> pl.population;
cout << "Enter planet's acceleration of gravity: ";
cin >> pl.g;
finout.write((char *) &pl, sizeof pl) << flush;
if (finout.fail())
{
cerr << "Error on attempted write\n";
exit(5);
}
// show revised file
ct = 0;
finout.seekg(0); // go to beginning of file
cout << "Here are the new contents of the " << file
<< " file:\n";
while (finout.read((char *) &pl, sizeof pl))
{
cout << ct++ << ": " << setw(20) << pl.name << ": "
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << "\n";
}
finout.close();
return 0;
}
// randomds.cpp -- draft standard random access to a binary file
#include <iostream.h> // not required by most systems
#include <fstream.h>
#include <stdlib.h> // for exit()
struct planet
{
char name[20]; // name of planet
double population; // its population
double g; // its acceleration of gravity
};
const char * file = "planet.dat";
int main(void)
{
planet pl;
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::right, ios::adjustfield);
// show initial contents
ios::openmode fmode = ios::in | ios::out | ios::ate | ios::binary;
ifstream fin(file,fmode); // associate input stream with a fiel
ostream fout(fin.rdbuf()); // associate output stream with same file
streampos end;
streampos now;
int ct = 0;
if (fin.good())
{
end = fin.rdbuf()->pubseekoff(0,ios::end, fmode); // locate file end
now = fin.rdbuf()->pubseekoff(0,ios::beg, fmode); // go to beginning
cout << "Here are the current contents of the "
<< file << " file:\n";
while (now != end)
{
fin.read((char *) &pl, sizeof pl); // read a block
now = fin.rdbuf()->pubseekoff(0,ios::cur, fmode);
// now is new location
cout << ct++ << ": " ;
cout.width(20);
cout << pl.name << ": ";
cout.precision(0);
cout.width(12);
cout << pl.population;
cout.precision(2);
cout.width(6);
cout << pl.g << "\n";
}
if (fin.eof())
fin.clear(); // clear eof flag
}
else
{
cerr << file << " could not be opened -- bye.\n";
exit(2);
}
// change a record
cout << "Enter the record number you wish to change: ";
long rec;
cin >> rec;
while (cin.get() != '\n')
continue; // get rid of newline
if (rec < 0 || rec >= ct)
{
cerr << "Invalid record number -- bye\n";
exit(3);
}
streamoff offset = rec * sizeof pl;
now = fin.rdbuf()->pubseekoff(offset,ios::beg, fmode);
if (fin.fail())
{
cerr << "Error on attempted seek\n";
exit(4);
}
fin.read((char *) &pl, sizeof pl);
cout << "Your selection:\n";
cout << rec << ": ";
cout.width(20);
cout << pl.name << ": ";
cout.precision(0);
cout.width(12);
cout << pl.population;
cout.precision(2);
cout.width(6);
cout << pl.g << "\n";
if (fin.eof())
fin.clear(); // clear eof flag
cout << "Enter planet name: ";
cin.getline(pl.name, 20);
cout << "Enter planetary population: ";
cin >> pl.population;
cout << "Enter planet's acceleration of gravity: ";
cin >> pl.g;
fout.rdbuf()->pubseekoff(offset, ios::beg, fmode); // go back
fout.write((char *) &pl, sizeof pl) << flush;
if (fout.fail())
{
cerr << "Error on attempted write\n";
exit(5);
}
// show revised file
ct = 0;
now = fin.rdbuf()->pubseekoff(0,ios::beg,fmode); // go to beginning
cout << "Here are the new contents of the " << file
<< " file:\n";
while (now != end)
{
fin.read((char *) &pl, sizeof pl);
now =fin.rdbuf()->pubseekoff(0, ios::cur, fmode);
cout << ct++ << ": " ;
cout.width(20);
cout << pl.name << ": ";
cout.precision(0);
cout.width(12);
cout << pl.population;
cout.precision(2);
cout.width(6);
cout << pl.g << "\n";
}
fin.close();
return 0;
}
// strout.cpp -- incore formatting (output)
#include <iostream.h>
#include <strstream.h>
const int LIM = 20;
int main(void)
{
ostrstream outstr; // manages a char array
char hdisk[LIM];
cout << "What's the name of your hard disk? ";
cin.getline(hdisk, LIM);
int cap;
cout << "What's its capacity in MB? ";
cin >> cap;
// write formatted information to array
outstr << "The hard disk " << hdisk << " has a capacity of "
<< cap << " megabytes.\n";
outstr.put('\0'); // make it a string
char * po = outstr.str(); // get address of array
cout << po; // show contents
delete po; // free memory
return 0;
}
// strin.cpp -- formatted reading from a char array
#include <iostream.h>
#include <strstream.h>
const int LIM = 20;
int main(void)
{
char buf[] = "It was a dark and stormy day, and "
" the full moon glowed brilliantly.";
istrstream instr(buf, sizeof buf); // use buf for input
char word[LIM];
while ((instr >> word).good()) // read a word a time
cout << word << endl;
return 0;
}