Counting the number of words in a file
<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;fstream&gt;
#include &lt;cstring&gt;

using namespace std;

int hmlines(ifstream &amp;a){
int i=0;
string line;
while (getline(a,line)){
cout &lt;&lt; line &lt;&lt; endl;
i++;

}
return i;

}


int hmwords(ifstream &amp;a){

int i=0;
char c;
while ((c=a.get()) &amp;&amp; (c!=EOF)){
if(c==' '){
i++;
}

}

return i;


}








int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout &lt;&lt; "give me the name of the file i wish to count lines, words and chars: ";
cin &gt;&gt; filename;
matos.open(filename.c_str());
if (matos.fail()){
goto start;
}
l = hmlines(matos);
matos.seekg(0, ios::beg);
w = hmwords(matos);
/*c = hmchars(matos);*/
cout &lt;&lt; "The # of lines are :" &lt;&lt; l &lt;&lt; ". The # of words are : " &lt;&lt; w ;

matos.close();



}
</code></pre>

<p>The file that i am trying to open has the following contents.</p>

<pre><code>Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
</code></pre>

<p>The output i get is:</p>

<pre><code>give me the name of the file i wish to count lines, words and chars: ert.txt
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
The # of lines are :4. The # of words are : 0
</code></pre>
