Issue with counting upper and lower letters in C

Viewed 61

I've written a program which should count upper and lower letters and other signs but it counts anything but when I click Enter and then ^C (EOF). I don't know how to jump over it, hope somebody can help me somehow <3

#include <stdio.h>
#include <ctype.h>

int main()
{
  char ch;
  int uppers = 0, lowers = 0, others = 0;


  while((ch = getchar()) != EOF)
  {
    if(islower(ch))
      lowers++;

    else if(isupper(ch))
      uppers++;

    else
      others++;
  }

  printf("\n\nUpper letters - %d  Lower letters - %d   Others- %d", uppers, lowers, others);


  return 0;
}
2 Answers

Ctrl+C sends a SIGINT which normally just terminates your application.

What you need is Ctrl+D, which triggers EOF.

EDIT: Note that on Windows' default shell you may need Enter, Ctrl+Z, Enter (or F6) instead (though Ctrl+Z does something else entirely in Linux shells, sending a SIGSTOP). See this question.

You could also compare against 0xD instead of EOF to catch Enter, or maybe use 0x1B which will catch Esc. This way you avoid the weirdness of how to trigger the end-of-input on different platforms (unless you want to process an input stream).

Also take a look at this comment above as well as this answer which contain important additional info that I was missing!

CherryDt has already provided an appropriate answer.


But just to add to that, EOF is not a character but instead an end condition. It may be OS dependent. You can't rely on it to work the same manner in every environment. My suggest would be to use any character itself as a condition to terminate loop, rather than an condition which is environment dependent.

NOTE : The solution worked of ending the program with keys worked for me on Windows only when I included a fflush(stdin); after the getchar(). Probably, getchar() takes the input you give and leaves newline character \n in the input stream which was causing problem when I tried to terminate using ctrl+D or ctrl+Z or F6.

But once you include fflush(stdin), this would solve the problem and now the program ends successfully when I use the F6 on Windows. You can also try with above mentioned keys if this does not work for you.

Hope this helps some Windows users if the above answer wasn't working for them.

Related