Reputation: 167
I have a really large file containing more than a million characters including spaces and newlines. I was able to find the number of occurrences of one character,
ifstream inData;
inData.open("info.txt");
char text;
int achar=0;
while (inData >> text)
{
if (text == 'a')
{
achar++;
}
}
cout << achar;
I can expand this to all the characters but that will take more than 60 lines of code. At face value, using a for loop to span through the characters, appears to be a solution. However, the text isn't sorted so it will not work in the while loop. I attempted to insert the inData into a string. Once again, due to the fact that there are newlines it only took part of the text. So, I thought maybe using an array might help, but in light of the huge number of characters; it is not only hard to predict how many characters there are, but it also entails doing a loop more than a million times. Clearly, that isn't a wise route. Is there an effective way of doing this?
Upvotes: 1
Views: 79
Reputation: 114461
Just use an array for the counters:
int count[256] = {0};
unsigned char c;
while (inData >> c) {
count[c]++;
}
Upvotes: 6