Google
 

Monday, January 10, 2011

C++ Primer, Fourth Edition Notes Chapter 8 Exercise

Exercise 8.1:

Assuming os is an ofstream, what does the following program do?

    os << "Goodbye!" << endl;

What if os is an ostringstream? Whatif os is an ifstream?

Answer:

ofstream: write the “Goodbye” and endl to file

ifstream:ERRO

ostringstream: write the string to string stream

Exercise 8.2:

The following declaration is in error. Identify and correct the problem(s):

    ostream print(ostream os);

reason: the stream can be copied and only be referenced or use the pointer


Exercise 8.3:

Write a function that takes and returns an istream&. The function should read the stream until it hits end-of-file. The function should print what it reads to the standard output. Reset the stream so that it is valid and return the stream.

Exercise 8.4:

Test your function by calling it passing cin as an argument.

// Exercise 8.3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
ifstream &printOut( ifstream &in);
istream &print( istream &in);
int main(int argc, _TCHAR* argv[])
{
ifstream in("ReadMe.txt");

ifstream &inf = printOut(in);

if(inf)
{
cout << "Testing the stream input;" << endl;
string s;
//Issue here: already clear the stream, but the stream still can't be reused
while(inf >> s , !inf.eof())
{
cout << s << endl;
}
inf.close();
}

print(cin);
// test the cleared eofbit mark
if(cin.eof())
{
//why it always show it is not cleared here?
cout << "the eof mark is not cleared!" << endl;
}
else
cout << "the eof mark is cleared!" << endl;
int i(0);
cin >> i;
return 0;
}


ifstream &printOut( ifstream &in)
{
string s;
while(in >> s , !in.eof())
{
//print out all to standard output
cout << s << endl;
}
//reset the stream
in.clear( istream::eofbit);
//in.setstate( istream::eofbit);

return in;
}
istream &print( istream &in)
{
string s;
while(in >> s , !in.eof())
{
//print out all to standard output
cout << s << endl;
}
if(in.eof())
{
cout << "The end of file!" << endl;
}
// clear the eofbit mark
in.clear( istream::eofbit);

return in;
}

Exercise 8.5:

What causes the following while to terminate?

    while (cin >> i) /* . . . */

Answer: when the cin is not available, one of the bits are set: eofbit, badbit, failbit.


Exercise 8.6:

Because ifstream inherits from istream, we can pass an ifstream object to a function that takes a reference to an istream. Use the function you wrote for the first exercise in Section 8.2 (p. 291) to read a named file.

// Exercise 8.6.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
ifstream &printOut( ifstream &in);
istream &print( istream &in);
int main(int argc, _TCHAR* argv[])
{
ifstream in("ReadMe.txt");

print( in);

int i(0);
cin >> i;
return 0;
}
istream &print( istream &in)
{
string s;
while(in >> s , !in.eof())
{
//print out all to standard output
cout << s << endl;
}
if(in.eof())
{
cout << "The end of file!" << endl;
}
// clear the eofbit mark
in.clear( istream::eofbit);

return in;
}

Exercise 8.7:

The two programs we wrote in this section used a break to exit the while loop if the open failed for any file in the vector. Rewrite these two loops to print a warning message if a file can't be opened and continue processing by getting the next file name from the vector.

// Exercise 8.7.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void process(string s);

int main(int argc, _TCHAR* argv[])
{
vector<string> *files = new vector<string>();
string p[] = {
"Debug",
"Exercise 8.7.cpp",
"Exercise 8.7.vcxproj",
"Exercise 8.7.vcxproj.filters",
"Exercise 8.7.vcxproj.user",
"list.txt",
"ReadMe.txt",
"stdafx.cpp",
"stdafx.h",
"targetver.h"};

for (int i = 0; i < 10 ; ++i)
{
files->push_back( p[i] );
}
ifstream input;
vector<string>::const_iterator it = (*files).begin();
string s;
// for each file in the vector
while (it != (*files).end()) {
input.open(it->c_str()); // open the file
// if the file is ok, read and "process" the input
if (!input)
{
// error , print out message
cout << "To open the file:" << *it << " is failed!" << endl;
}
else
{
while(input >> s) // do the work on this file
process(s);
}
input.close(); // close file when we're done with it
input.clear(); // reset state to ok
++it; // increment iterator to get next file
}

return 0;
}

void process(string s)
{
cout << s << endl;
}

Exercise 8.8:

The programs in the previous exercise can be written without using a continue statement. Write the program with and without using a continue.

see Exercise 8.7

Exercise 8.9:

Write a function to open a file for input and read its contents into a vector of strings, storing each line as a separate element in the vector.

// Exercise 8.9.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

int getline(ifstream &in, string &s);

int main(int argc, _TCHAR* argv[])
{
ifstream in("ReadMe.txt");

vector<string> vect;
char carray[1000];
while(in.getline(carray,1000))
{
vect.push_back(carray);
}

// print out;
vector<string>::iterator it = vect.begin();
while(it != vect.end())
cout << *it++ << endl;

int i;
cin >> i;
return 0;
}

Exercise 8.10:

Rewrite the previous program to store each word in a separate element.

// Exercise 8.10.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
ifstream in("ReadMe.txt");

vector<string> vect;
string s;
while( in >> s , !in.eof())
{
vect.push_back(s);
}
// print out
vector<string>::iterator it = vect.begin();
while(it != vect.end())
cout << *it++ << endl;

int i;
cin >> i;

return 0;
}

Exercise 8.11:

In the open_file function, explain why we call clear before the call to open. What would happen if we neglected to make this call? What would happen if we called clear after the open?

Answer: Before open to neglect to call clear, it will fail to open the file if there any error bit was set. After the open to call clear, it will reset the state of the stream just opened.

Exercise 8.12:

In the open_file function, explain what the effect would be if the program failed to execute the close.

Answer: to open the new file will be failed.

Exercise 8.13:

Write a program similar to open_file that opens a file for output.

// Exercise 8.13.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;
void open_file( ofstream &out, const string filename);
int main(int argc, _TCHAR* argv[])
{
ofstream out;
cout << "Please input the filename to save:" << endl;

string filename = "";
cin >> filename;
open_file(out, filename);
// print out content line by line
if(out)
{
cout << "Please input strings (\\n for break):" << endl;
string line;
while(cin >> line, !cin.eof())
{
if(line == "\\n")
break;
out << line << endl;
}
//out.flush();
// to save to file
out.close();
}

int i ;
cin >> i;

return 0;
}

void open_file( ofstream &out, const string filename)
{
// clear out state
out.clear();
out.close();
// open file
out.open(filename.c_str());
//return
return;
}

Exercise 8.14:

Use open_file and the program you wrote for the first exercise in Section 8.2 (p. 291) to open a given file and read its contents.

// Exercise 8.14.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;
void open_file( fstream &out, const string filename);

int main(int argc, _TCHAR* argv[])
{
fstream fst;

string filename;
cout << "Please input the file to open:" << endl;
cin >> filename;

open_file(fst, filename);
if(fst)
{
char line[1000];

while(fst.getline(line,1000))
cout << line << endl;
}

int i;
cin >> i;
return 0;
}

void open_file( fstream &out, const string filename)
{
// clear out state
out.clear();
out.close();
// open file
out.open(filename.c_str());
//return
return;
}

Exercise 8.15:

Use the function you wrote for the first exercise in Section 8.2 (p. 291) to print the contents of an istringstream object.

// Exercise 8.15.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <sstream>

using namespace std;

void printOut(istream &in);
int main(int argc, _TCHAR* argv[])
{

cout << "Please input strings(\\n for break):" << endl;
string s;
string result;
while(cin >> s)
{
if( s == "\\n")
break;
result+=s;
}
// the result string changed after binding with stringstream will not reflashed to the stream
istringstream istring(result.c_str());
printOut(istring);
int i;
cin >> i;
return 0;
}

void printOut(istream &in)
{
string s;
while(in >> s)
{
cout << s << endl;
}
}

Exercise 8.16:

Write a program to store each line from a file in a vector<string>. Now use an istringstream to read each line from the vector a word at a time.

No comments: