Reading text from a file. I think I did this correctly but wanted to see if someone could look over the loop and give me their two cents. I just want to make sure the approach I took would be the right way.
/**
* @author Your First Name and Last Name
* @file characterStats.cpp
*
* Program reads text from a text file named "characterStats.txt"
* and writes out the number of characters in the file, along with the
* number of letters and the number of non-whitespace characters. */
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cctype>
usingnamespace std;
int main( )
{
// Declare input stream
ifstream fin;
char val;
int count = 0;
int nws = 0;
int letters = 0;
// Open the file
fin.open("characterStats.txt");
// Check for successful file open
if ( fin.fail() ) // checking to see if successfully opened file
{
cerr << "Input file opening failed.\n" << endl; //error message
exit(1);
}
// Loop to read from file
// Count the number of characters along with
// the number of letters and non-whitespace characters
/* Below is what I wrote */
fin >> val;
do{
++count; // All characters including whitespace
if(std::isalpha(val))
++letters; //counting number of letters
if (std::isspace(val)) //counting the number of spaces
++nws;
}while(fin.get(val) );
nws = count - letters - nws; //subtracting the number of spaces and letters from total # of characters.
// Close the file
fin.close();
cout << "The file contains:\n";
cout << " " << count << " characters\n";
cout << " " << nws << " non-whitespace characters\n";
cout << " " << letters << " letters\n";
return 0; // successful completion
}
}
The text given was:
This is a test. Here's a number: 7.
Here's a second line of text.
You will have a problem if you enter emty file or file containing only space characters. Also you program skips leading whitespaces in the beginning of file.
To solve this change loop from do-while to just while and remove line 42.