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. */
int main( )
// Declare input stream
int count = 0;
int nws = 0;
int letters = 0;
// Open the file
// Check for successful file open
if ( fin.fail() ) // checking to see if successfully opened file
cerr << "Input file opening failed.\n" << endl; //error message
// 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;
++count; // All characters including whitespace
++letters; //counting number of letters
if (std::isspace(val)) //counting the number of spaces
nws = count - letters - nws; //subtracting the number of spaces and letters from total # of characters.
// Close the file
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.