int main(int argc, char** argv) 
{

      FILE *f;

      char  string[100];
      int counter=0;



      f=fopen("New Text Document.txt","r");
      if (f==NULL)
      {
        printf("error");
      }
        while(!feof(f))
        {


          fscanf(f,"%c",&string); 



        }
         fclose(f);

        for(int i=0;i<100;i++)
        {
            if (string[i]=='a')  /*doesnt work, why?*/
            {

                counter++;
            }
        }



        printf("\n the number of vowels a is : %d",counter);
        getch();
        return 0;
        }

the counter does not increment, i m not sure why.

Recommended Answers

All 4 Replies

First and foremost, your code exhibits undefined behavior because you only ever initialize the first character of the string. The actual problem you're seeing though, is that you only store one character at a time in string[0], and it gets replaced with each iteration of the file reading loop.

The counter will only increment if the last character in the file is 'a', or the random memory used by string happens to have an 'a' in it.

A better approach would be to read a character, then check it:

int ch;

while ((ch = fgetc(f)) != EOF) {
    if (ch == 'a') {
        ++counter;
    }
}

fclose(f);
commented: tnx! +3

tnx man, when you said "replaced" i automatically figured out that i should have done

while(!feof(f))
        {


          fscanf(f,"%c",&string[i]); 
          i++;
        }

this, and then loop through but tnx for that snippet

Using feof() like that may produce unexpected behavior, such as counting the last line twice. That's why it's better to loop like Deceptkion wrote it.

Is there a reason why your program is reading the file one character at a time instead of calling fscanf() to read an entire line at once?

Are you doing anything with the characters after counting them? If not, storing them is a waste of memory and also inflexible because you're shoehorned into the 100 character upper limit (using arrays at least).

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.