Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch and default: for C

Sorry if this sounds like a very basic question, it is my first time on here!

I am having some difficulties with coding for C, specifically with a switch and the default of that switch. Here is some example code:

#include<stdio.h>

int key;
main()
{
while((key=getchar())!=EOF)
{
printf("you pressed %c \n",key);
    switch(key){
case'0':
case'1':
case'2':
case'3':
   printf("it's a numeral\n");
   break;
default:
   printf("it's not a numeral\n");
  } 
 }
}

The actual code is a bunch longer, this is purely an example.

So the code compiles it and I execute it, but I get:

"You pressed 1, it's a numeral, you pressed , it's not a numeral."

My code seems to 'fall through' and repeat itself without referring to either one. If anyone could help that would be great as this is an example in a text book and I am utterly stuck!

Kindest Regards.

like image 397
Chalk Avatar asked Feb 01 '26 06:02

Chalk


1 Answers

You need to account for entering the Enter key, which produces a '\n' on *nix systems. I am not sure what pressing the Enter key does on Windows systems.

Here's your original code doctored up to eat the return key.

#include<stdio.h>

int key = 0;
main()
{
    while((key=getchar())!=EOF)
    {
        if('\n' == key)
        {
            /* Be silent on linefeeds */
            continue;
        }

        printf("you pressed %c \n",key);
            switch(key){
        case'0':
        case'1':
        case'2':
        case'3':
           printf("it's a numeral\n");
           break;

        default:
           printf("it's not a numeral\n");
      } 
     }
}

You maybe using getchar() for a specific reason, but my experiences in C usually involved reading the whole line, and RTL functions like scanf will eat the line terminator for you.

like image 90
octopusgrabbus Avatar answered Feb 03 '26 20:02

octopusgrabbus