#include <iostream> // cin, cout
#include <fstream> // ifstream, ofstream
#include <string> // string, getline()
#include <cassert> // assert()
#include <cfloat> // DBL_MIN and DBL_MAX
using namespace std;
int main()
{
cout << "This program computes the number, maximum, minimum, and\n"
<< "average of an input list of numbers in one file,\n"
<< "and places its results in another file.\n\n";
// ----------- Input Section -----------------------------------
cout << "Enter the name of the input file: ";
string inputFileName;
getline(cin, inputFileName); // get name of input file
// open an input stream
ifstream inStream; // to the input file,
inStream.open(inputFileName.data()); // establish connection,
assert( inStream.is_open() ); // and check for success
int count = 0; // number of values
double reading, // value being processed
maximum = DBL_MIN, // largest seen so far
minimum = DBL_MAX, // smallest seen so far
sum = 0.0; // running total
for (;;) // loop:
{
inStream >> reading; // read a value
if ( inStream.eof() ) break; // if eof, quit
count++; // update: count,
sum += reading; // sum,
if (reading < minimum)
minimum = reading; // minimum,
if (reading > maximum)
maximum = reading; // maximum
} // end loop
inStream.close(); // close the connection
// ------------ Output Section ---------------------------------
cout << "Enter the name of the output file: ";
string outputFileName;
getline(cin, outputFileName);
// open an output stream
ofstream outStream(outputFileName.data()); // to the output file,
// establish connection,
assert( outStream.is_open() ); // and check for success
// write results to file
outStream << "\n--> There were " << count << " values";
if (count > 0)
outStream << "\n\tranging from " << minimum
<< " to " << maximum
<< "\n\tand their average is " << sum / count
<< endl;
outStream.close(); // close the stream
cout << "Processing complete.\n";
}
|
Sample run #1: This program computes the number, maximum, minimum, and average of an input list of numbers in one file and places its results in another file. Enter the name of the input file: test1.dat Please enter the name of the output file: test1.out Processing complete. Listing of test1.out: --> There were 5 values ranging from 11 to 15 and their average is 13. Sample run #2: This program computes the number, maximum, minimum, and average of an input list of numbers in one file and places its results in another file. Enter the name of the input file: test2.dat Please enter the name of the output file: test2.out Processing complete. Listing of test2.out: --> There were 9 values ranging from 91 to 99 and their average is 95. |
#include <iostream> // cin, cout, >>, <<
#include <fstream> // ifstream, ofstream
#include <string> // string, getline()
using namespace std;
// --- Open an ifstream interactively ---------------------
void interactiveOpen(ifstream & theIFStream)
{
char response;
do
{
cout << "Enter the name of the input file: ";
string inputFileName;
getline(cin, inputFileName);
theIFStream.open(inputFileName.data());
if (theIFStream.is_open()) break;
cerr << "\n***InteractiveOpen(): unable to open "
<< inputFileName << "\nTry again (Y or N)? ";
cin >> response;
}
while (response != 'N' && response != 'n');
}
// --- Open an ofstream interactively ---------------------
void interactiveOpen(ofstream & theOFStream)
{
char response;
do
{
cout << "Enter the name of the output file: ";
string outputFileName;
getline(cin, outputFileName);
theOFStream.open(outputFileName.data());
if (theOFStream.is_open()) break;
cerr << "\n***InteractiveOpen(): unable to open "
<< outputFileName << "\nTry again (Y or N)? ";
cin >> response;
}
while (response != 'N' && response != 'n');
}
|
#include <iostream> // cin, cout, <<, >>
#include <fstream> // ifstream, open(), close(), eof()
#include <string> // string, getline(), find(), NPOS
using namespace std;
void interactiveOpen(ifstream & theIFStream);
int main()
{
cout << "This program searches a file for a given string.\n";
ifstream inStream;
interactiveOpen(inStream);
// get the search string
cout << "Enter the string being sought: ";
string searchString;
getline(cin, searchString);
string lineOfText;
for (;;)
{
getline(inStream, lineOfText); // get a line from the file
if ( inStream.eof() ) break; // quit, if at eof
// display a "found" msg.
if (lineOfText.find(searchString, 0) != string::npos)
cout << "\n*** " << searchString
<< " found in this file." << endl;
}
cout << "\nProcessing complete.\n"; // message to user
nStream.close(); // close the file
}
/*** Insert the definition of the function interactiveInput() from Figure 9.3 here. ***/ ---------------------------------------------- Listing of simulated virus-infected file: aisjdfklasdjfklasjfljasdfljasdas;l zzmANTIkladfklajsdfklajsdfkjasdljaslkdfj kasjfklasdjfklajsdfkljasdflkalskdf kjavjdfjoiwjefmm,.xmcjeoieCewmp.EM ,mckwjoaejcccnmeyquvhi hnrefnnfhDKFa nacjksnfhean, ae lcajwefawefmaklmefl;m ckmadjeoiemaamcl;maelalskmclamsl;k --------------------------------------------- Sample run: This program searches a file for a given string. Enter the name of the input file: binary.sim Please enter the string being sought: ANTI *** ANTI found in this file. Processing complete. |
#include <iostream> // cout, <<, >>
#include <fstream> // ifstream, is_open(), eof(), clear(), seekg()
#include <cassert> // assert
using namespace std;
int main()
{
ifstream inStream("data.txt");
assert(inStream.is_open());
double newValue,
sum = 0.0,
average = 0.0;
int count = 0;
for (;;)
{
inStream >> newValue;
if (inStream.eof()) break;
sum += newValue;
count++;
}
if (count > 0) average = sum / count;
inStream.clear(); // clear eof bit
inStream.seekg(0, ios::beg); // reset read position
for (;;)
{
inStream >> newValue;
if (inStream.eof()) break;
cout << newValue << ": " << newValue - average << endl;
}
inStream.close();
}
|
void readColor(istream & theStream, string & theColor)
{
string theWord;
theStream >> theWord;
if (theWord == "red" || theWord == "orange" ||
theWord == "yellow" || theWord == "green" ||
theWord == "blue" || theWord == "indigo" ||
theWord == "violet")
theColor = theWord;
else
{
theStream.seekg(-theWord.size(), ios::cur); // unread the word
theStream.setstate(ios::failbit); // indicate failure
}
}
|
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
int main()
{
string date = "Independence Day: July 4, 1776";
istringstream istr(date);
string word1, word2, month;
int day, year, one = 1;
char comma;
istr >> word1 >> word2 >> month >> day >> comma >> year;
cout << "Contents of string stream istr:\n"
<< word1 << "***" << word2 << "***" << month << "***"
<< day << "***" << comma << "***" << year << endl;
ostringstream ostr;
ostr << "New Year's "<< word2 << "January"
<< setw(2) << one << ", "<< year + 226;
cout << ostr.str() << endl;
}
---------------------------------------
Sample run:
Contents of string stream istr:
Independence***Day:***July***4***,***1776
New Year’s Day: January 1, 2002
|
#include <iostream> // cout
#include <fstream> // ifstream
#include "Name.h"
using namespace std;
int main()
{
ifstream fin("nameFile.txt");
Name aName;
for (;;)
{
aName.read(fin);
if ( fin.eof() ) break;
aName.print(cout);
}
fin.close();
}
----------------------------
Sample run:
John Jacob Jingle-Heimer-Schmidt
Little Bo Peep
Little Jackie Horner
Yertle the Turtle
|
#include <string> // class string
#include <sstream> // istringstream, ostringstream
using namespace std;
class Name
{
public:
// ... other constructors omitted ...
Name(string fullName); // convert string to Name
string asString() const; // convert Name to string
// ... other methods omitted ...
private:
string myFirstName, myMiddleName, myLastName;
};
// Definitions of converters
inline Name::Name(string fullName)
{
istringstream ssin(fullName);
ssin >> myFirstName >> myMiddleName >> myLastName;
}
inline string Name::asString() const
{
return myFirstName + ' ' + myMiddleName + ' ' + myLastName;
}
|
#include <string> // class string
#include <iostream> // cin, cout, ...
using namespace std;
#include "Name.h"
int main()
{
string fullNameString = "Horace Debussey Jones";
Name aName(fullNameString); // convert string to Name
string nameString = aName.asString(); // convert Name to string
aName.print(cout); // output Name
cout << "\n" << nameString << endl; // output string
}
-----------------------------
Sample Execution:
Horace Debussey Jones
Horace Debussey Jones
|
#include <string> // class string
#include <sstream> //istringstream, ostringstream
using namespace std;
class Sphere
{
public:
// ... other constructors omitted ...
Sphere(string sphereAttributes); // convert string to Name
string asString() const; // convert Sphere to string
// ... other methods omitted ...
private:
double myRadius, myDensity, myWeight;
};
inline Sphere::Sphere(string sphereAttributes)
{
istringstream ssin(sphereAttributes);
ssin >> myRadius >> myDensity >> myWeight;
}
inline string Sphere::asString() const
{
ostringstream ssout;
ssout << myRadius << ' ' << myDensity << ' ' << myWeight;
return ssout.str();
}
|
#include <string> // class string #include <iostream> // cin, cout, ... #include <fstream> // ifstream, ofstream #include "Sphere.h" using namespace std; int main()
{
cout << "\nTo compute the weight of a sphere,\n"
<< " enter its radius and density: ";
Sphere aSphere;
aSphere.readRadiusAndDensity(cin);
// store aSphere in a file
ofstream fout("Sphere.txt");
fout << "Sphere\n" << aSphere.asString() << endl;
fout.close();
// now, read info back
ifstream fin("Sphere.txt");
string classString, attributeString;
getline(fin, classString);
getline(fin, attributeString);
fin.close();
// rebuild object
if (classString == "Sphere")
{
Sphere sameSphere(attributeString);
sameSphere.print(cout);
cout << endl;
}
else
{
cerr << "Unexpected class: " << classString << endl;
exit(1);
}
}
--------------------------------
Sample Execution:
To compute the weight of a sphere,
enter its radius and density: 6.5 14.6
Sphere, radius: 6.5, density: 14.6, weight: 16795
--------------------------------
Contents of file Sphere.txt:
Sphere
6.5 14.6 16795
|