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;

}

Dani AI

Generated

's single-loop suggestion is the right direction; it avoids a second pass over the file and keeps counting and total-word tracking together. 's updated program already works for simple cases but has three common gaps that cause wrong results in real text files: (1) file-open failure is reported but the program keeps running (risking a divide-by-zero), (2) punctuation and case differences make token == search miss matches (e.g. "word," vs "word"), and (3) operator>> leaves punctuation attached to tokens. Addressing those makes the tool reliable.

A compact, practical checklist:

  • Exit immediately if the file cannot be opened (do not continue to counting).
  • Normalize both the search term and every token before comparing: convert to lower-case and strip non-alphanumeric characters. This handles "Word", "word.", and "word," equally.
  • Always guard the frequency calculation against a zero total-word count.

A minimal C++ pattern that implements these fixes (normalization + single loop):

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

static std::string normalize(const std::string& s){
    std::string out;
    for(unsigned char c: s) if(std::isalnum(c)) out += std::tolower(c);
    return out;
}

// open file, check success, normalize search term, then:
std::string token, search = normalize("userWord");
long total = 0, hits = 0;
std::ifstream in("input.txt");
if(!in) return 1;
while(in >> token){
    ++total;
    if(normalize(token) == search) ++hits;
}
if(total) std::cout << hits << " / " << total << "  (" << (double)hits/total << ")\n";

Note for : the same approach applies in C — use fopen, read lines with fgets, split with strtok (or manual scanning), build a normalized buffer using tolower and isalnum, then strcmp to compare. For phrase matching or very large files, switch to line-based searching or streaming algorithms rather than token-by-token memory buffering.

Recommended Answers

All 5 Replies

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.