wii anybody plz tell me that how can we count a char in file when it repeats;

First, please use proper English (i.e. not "plz") when posting on Daniweb.

I would use an std::map. Traverse the string a character at a time. If the element doesn't exist in the map, add it to the map as a key with value=1. If it does already exist in the map, increment the associated value.

Dave

thankz

Again, "thankz" is not proper English.

well sorry.
thanks

> I would use an std::map.
Unless the problem is likely to become more general, there is no need for the overhead of a map.

int count = 0;
char c;

while (fin.get(c)) {
    if (c == 'A')
        ++count;
}

cout << "There are " << count << " 'A's in the file\n";

The map method works best when the number of unique items being counted is large enough to make a linear search too slow or unknown enough to warrant dynamic allocations.

You're right Ed, but I was assuming he wanted to find the frequency of more than 1 letter.

Not compiled.

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
using namespace std;

int main(){
 std::ifstream fileReader("text.txt");
 std::string content;
 std::string temp;
 while( getline(fileReader,temp) ){ content += temp; }
 
 char letterToFind = 'A';
 int count = std::count(content.begin(),content.end(),letterToFind);
 cout << count << " occurrence of '" << letterToFind << "'\n";
}

Good use of the STL, firstPerson. You can make it even shorter by using istream iterators instead of manually loading a string.

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>

int main()
{
    std::ifstream ifs("test.txt");
    int count = std::count(
        std::istream_iterator<char>(ifs), 
        std::istream_iterator<char>(), 
        'A');

    std::cout << count << '\n';
}
commented: nice 1 +5
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.