Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ count() function displays 1's and 0's rather than a total count when reading from a text file

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading