Ad

Issue With Counting Upper And Lower Letters In C

- 1 answer

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;
}
Ad

Answer

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!

Ad
source: stackoverflow.com
Ad