Answer to Question #274049 in C++ for Amit

Question #274049

Write a program to count the number of words present in a file.

1
Expert's answer
2021-12-09T07:30:13-0500
#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.";
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment