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.


> 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')

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.

Edited 6 Years Ago by Radical Edward: n/a

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";

Edited 6 Years Ago by firstPerson: n/a

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::cout << count << '\n';
nice 1
This article has been dead for over six months. Start a new discussion instead.