C++ Primer Plus Chapter 6 Exercise 8

c++IconWe create a simple file reading program in exercise 8. As usual, there where a couple of ways to accomplish this. I chose to declare my input file, and as long as we did not receive and error opening the file or reach end of file, use isprint to count any characters in the file. Mind you “file.txt” is to be placed in the same directory as your program with some characters in it. See my source below:

8. Write a program that opens a text file, reads it character-by-character to the end of the file, and reports the number of characters in the file.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
ifstream inFile;

// Fail-safe
if (!inFile.is_open())
cout << "Failed to open: " << inFile << endl;
cout << "Kthxby" << endl;

char letter;
int count = 0;
inFile >> letter;
while (!inFile.eof())
if (isprint(letter))
inFile >> letter;

cout << "\n" << "Number of characters is: " << count << endl;

// Check for EOF
if (inFile.eof())
cout << "End of file found.\n";
else if (inFile.fail())
cout << "Data mismatch.\n";
cout << "Input terminated for unknown reason.\n";

// Clean


return 0;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s