C - Program only doing 1 part of a if else statement -
hey trying create program ask user letter count how many times letter appears in .txt document. have code 99% done whatever if statement put first 1 gives correct amount.
#include<stdio.h> #include<string.h> #include<ctype.h> #define n 61 // maximum size of file name file* open_file(void) { char file_name[n]; file* input_file; printf("enter name of input file: "); scanf("%s", file_name); input_file = fopen(file_name, "r"); while (input_file == null) { printf("\nerror: file not found \"%s\"\n", file_name); printf("re-enter file name: "); scanf("%s", file_name); input_file = fopen(file_name, "r");} return input_file;} void main() { char inputletter; char lowerletter; char upperletter; char chr; int upper; int lower; file* input_file = open_file(); printf("enter letter: "); scanf(" %c", &inputletter); lowerletter = tolower(inputletter); upperletter = toupper(inputletter); while(1){ chr = fgetc(input_file); if (chr == eof){ break; } else if(chr ==lowerletter){ lower++; } else if(chr == upperletter){ upper++; } } printf(" %c", inputletter); printf(" %c %d ", lowerletter, lower); printf(" %c %d ", upperletter, upper); }
when reading .txt document 22 lower case e , 2 capital 2 print
e e 22 e 258
if switch 2 if statements counter print
e e 278 e 2
what doing wrong wont count both correctly?
because never initialize upper
or lower
, try before while (1)
upper = 0; lower = 0;
and don't need kind of while (1)
loop think misleading, lot better if explicitly use break
condition loop, i.e.
while ((chr = fgetc(input_file)) != eof) { if (chr == lowerletter) lower += 1; else if (chr == upperletter) upper += 1; }