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;
inFile.open("file.txt");

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

char letter;
int count = 0;
inFile >> letter;
while (!inFile.eof())
{
if (isprint(letter))
count++;
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";
else
cout << "Input terminated for unknown reason.\n";

// Clean
inFile.close();

cin.get();

return 0;
}
Advertisements