counting the number of times a character appears in a file in a case insensitive manner using C language -
the problem statement : c program count number of times character appears in file. character considered case insensitive. have converted both input character , character file upper case none of occurrence of character goes uncounted. when executing on online editor getting result "wrong answer" editor isn`t accepting code. mistake in code??
#include<stdio.h> #include<ctype.h> #include<stdlib.h> int main { file *fp; char filename[20]; char character; char compare; int to_upper1; int to_upper2; int count=0; printf("\nenter file name"); scanf("%s", filename); fp = fopen(filename,"r"); if(fp == null) { exit(-1); } printf("\nenter character counted"); scanf("%c", &character); to_upper1 = toupper(character); while((compare = fgets(fp)) != eof) { to_upper2 = toupper(compare); if(to_upper1 == to_upper2) count++; } printf("\nfile \'%s\' has %d instances of letter \'%c\'", filename, count, character); return 0; }
i found few errors in code, , made few small tweaks. errors - not eating "whitespace" before character input, using fgets()
instead of fgetc()
, using escape characters before '
symbols in output text.
#include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(void) // added arg compilability { file *fp; char filename[20]; char character; int compare; // correct type fgetc , toupper int to_upper1; int to_upper2; int count=0; printf("enter file name: "); scanf("%19s", filename); // restrict length fp = fopen(filename,"r"); if(fp == null) { printf ("cannot open file '%s'\n", filename); exit(-1); } printf("\nenter character counted: "); scanf(" %c", &character); // filter out whitespace to_upper1 = toupper((int)character); while((compare = fgetc(fp)) != eof) // changed fgets() { to_upper2 = toupper(compare); if(to_upper1 == to_upper2) count++; } fclose(fp); // remember close file! printf("file '%s' has %d instances of letter '%c'", filename, count, character); return 0; }
Comments
Post a Comment