Write a program to count the number of words present in a file.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string fileName="test.txt";
//Opening file
ifstream in(fileName);
if(!in.is_open())
{
cout<<"Can`t open file!";
}
else
{
int words=0;
char c;
in.seekg(0,ios::beg);
while(!in.eof())
{
in.get(c);
if(isalpha(c)||isdigit(c))
{
words++;
while(c!=' '&&c!='\n'&&c!='\t')
in.get(c);
}
}
cout<<"File "<<fileName<<" has "<<words<<" words.";
}
}
Comments
Leave a comment