Input on if I did this I/O right.

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* @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>
using namespace 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.
Thanks again!
Topic archived. No new replies allowed.