0

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;

}
3
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by bharathmakawana
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.

0

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

0

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
}

Edited by jonsca: n/a

0

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;

}
-1

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

Votes + Comments
You've convinced me. I've sent the code, didn't you receive it?
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.