Home > OS >  how do Write a program to read the content from the saved text file and provide following output -Nu
how do Write a program to read the content from the saved text file and provide following output -Nu

Time:12-14

I have saved my text file, but im not sure as to how i should seperate the number and alphabet count.

i was able to do a character count. i tried turning the file into a string and doing it but ive had to type the entire contents of the file as a string again in when the output comes out.

CodePudding user response:

Here is the sample code

#include <stdio.h>

int main() {
  // Declare variables to store the counts of numbers and alphabets
  int numCount = 0;
  int alphaCount = 0;

  // Open the file in read-only mode
  FILE *fp = fopen("file.txt", "r");

  // Check if the file was successfully opened
  if (fp == NULL) {
    printf("Error: Unable to open file\n");
    return 1;
  }

  // Read the contents of the file one character at a time
  char ch;
  while ((ch = fgetc(fp)) != EOF) {
    // Check if the character is a number
    if (ch >= '0' && ch <= '9') {
      numCount  ;
    }
    // Check if the character is an alphabet
    else if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
      alphaCount  ;
    }
  }

  // Print the counts of numbers and alphabets
  printf("Number count: %d\n", numCount);
  printf("Alphabet count: %d\n", alphaCount);

  // Close the file
  fclose(fp);

  return 0;
}
  •  Tags:  
  • c
  • Related