I'm relatively new to this and need help counting the number of times a user provided word appears in a user provided file
this is what I got:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
	ifstream infile;
	string str, filename;
	int count, num;

	count = 0;
	num = 0;

	cout << "Enter File Name: \n";
	cin >> filename;

	infile.open(filename.c_str());
		if(!infile)
		{
			cout << "Error...Could not find file!!!\a";

		}

	cout << "Enter word to look for : \n";
	cin >> str;

	while ()		//Need help counting number of times the user
	{				//input word shows up in the user provided file...
		num++;
	}
	
	cout << str << ": " << num << "\n";
	
	while(infile >> str)
	{
			count++;
	}

	cout << "Frequency: " << (double)num/count << endl;

	return 0;

}

I would use 1 while loop (just like your second one) and put an if/else in there to distinguish between matched words and regular words and then up the count on each when appropriate.

how would you distinguish between the matched word and the regular word...i think that is my major problem..

Take the infile into not str (as that has your users word) but tempstring or something like that.

while(infile >> tempstring)
{
     if(tempstring == str)
         num++;

     count++; //do this regardless
}

Thank you very much here is new code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
	ifstream infile;
	string tempstr, str, filename;
	int count, num;

	count = 0;
	num = 0;

	cout << "Enter File Name: \n";
	cin >> filename;

	infile.open(filename.c_str());
		if(!infile)
		{
			cout << "Error...Could not find file!!!\a";

		}

	cout << "Enter word to look for : \n";
	cin >> str;
	
	while(infile >> tempstr)
	{
		if(tempstr == str)
		{
			num++;
		}
		
		count++;
	}

	cout << str << ": " << num << "\n";

	cout << "Frequency: " << (double)num/count << endl;

	return 0;

}

hey don mistake me.... ll u please code the above program in C instead of C++ bcoz i m new to the programming languages
thnx in advance

commented: You've convinced me. I've sent the code, didn't you receive it? -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.