When counting a simple string, this works:
string x = "aabbcc";
int n = count (x.begin(), x.end(), 'a');
cout << n;
This outputs ‘2’ which is correct.
However, when I read in the string from a text file:
ifstream myFile;
myFile.open(argv[1]);
string x;
if (myFile.is_open()) {
while (myFile) {
x = myFile.get();
int n = count(x.begin(), x.end(), 'a');
cout << n;
This outputs 0’s and 1’s, the 1’s appearing where the ‘a’s would appear.
Instead, I want a total count of a’s.
Thanks in advance.
>Solution :
get() function is extracting a character at a time and passing it to variable X.
in every iteration of the while loop, X is of size 1.
Variable n contains the counts of ‘a’ character in the One character X has in it.
so, your output is instead number of a’s in every single character of the file.
For the case when the character is actually ‘a’, You get to count that it found ONE count of a.
use this:
easy option:
change n to static
static int n = 0;
while (myFile) {
x = myFile.get();
n += count(x.begin(), x.end(), 'a');
}
cout<<n;
hard option
use a different get() function variation that gives you whole string. Pass that to string variable X