开发者

reading files using fgetc

I have a question about using fgetc to count characters in a specified file. How do you use it when you have to count character types separately? Like for example I only want 开发者_运维问答to count the number of lowercase characters only, or number of spaces, or punctuations, etc? Can someone show a brief example? Thank you

I tried to do this program that would hopefully count the total number of characters, how do you squeeze in though the number of the separate character types? I'm not exactly sure if this program is correct

#include <stdio.h>
int main (void)
{
    //Local declarations
    int a;
    int count = 0;
    FILE* fp;

    //Statements
    if (!(fp = fopen("piFile.c", "r")))
    {
    printf("Error opening file.\n");
    return (1);
}//if open error

      while ((a = fgetc (fp)) != EOF)
      {
      if (a != '\n')
      count++;
      printf("Number of characters: %d \n", count);

      else
      printf("There are no characters to count.\n");
      }
      fclose(fp);
      return 0;
}


Read up on these functions:

   int isalnum(int c);
   int isalpha(int c);
   int isascii(int c);
   int isblank(int c);
   int iscntrl(int c);
   int isdigit(int c);
   int isgraph(int c);
   int islower(int c);
   int isprint(int c);
   int ispunct(int c);
   int isspace(int c);
   int isupper(int c);
   int isxdigit(int c);

and you'll see right away how to do it.


In your while, you can use if statements for each character you want to check.

if(isalnum(a){
    counta++;
}
else if(isalpha(a)){
    countb++;
}
else if(isascii(a)){
    countc++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜