2

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.

Chalk
  • 33
  • 1
  • 5
  • 7
    You are not eating the `return` key. – user703016 May 20 '12 at 22:01
  • possible duplicate of [Why doesn't getchar() wait for me to press enter?](http://stackoverflow.com/questions/1391548/why-doesnt-getchar-wait-for-me-to-press-enter) – P.P May 20 '12 at 22:06

5 Answers5

1

You need to eat the newline character, that is put in the read buffer when you hit return.

Issue another call to getchar after or before the switch to solve your problem.

user703016
  • 37,307
  • 8
  • 87
  • 112
1

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.

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
  • On Windows it produces `\n` too, unless you are reading a text file opened in binary mode. – Matteo Italia May 20 '12 at 22:57
  • @MatteoItalia Thanks. I don't do a lot of command line reads anymore. Mostly it's inputting files. – octopusgrabbus May 20 '12 at 23:23
  • @octopusgrabbus thank you so much for your help. It works like a charm now! Just so I get my head around it completely, I am basically including an 'if' statement that tests whether '/n' is equal to my variable, and if it is... continues without displaying anything? If I am wrong let me know as I would really like to get a firm understanding of this before I move on! Thanks once again! – Chalk May 21 '12 at 11:33
  • @Chalk Depending on the kind of work you wind up doing in C, you may find you'll rely more on `scanf()` than `getchar()`, although `getchar()` is useful for a quick input for just one character. – octopusgrabbus May 21 '12 at 12:14
  • @octopusgrabbus I am simply just using it as a learning curve for other languages. I have to say, I am loving the simplicity of C! Just to clarify, in my previous comment was in correct in my understanding if your solution. Thanks once again for your help. – Chalk May 21 '12 at 13:45
0

Here is an idea...immediately before the printf(), insert logic to ignore spaces and all control characters...

if(key <= ' ')
  continue;
printf(...) ...
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
-1

I dont know if that is the problem, but you have three case without a break. So you press key "1" and there is nothing to do for the programm and so ins go to the next case how is right and this is the default. Although you take a char in an int-variable???

In your Example it is a better way to take a if-clause like this:

#include<stdio.h>

char key;
main()
{
while((key=getchar())!=EOF)
{
printf("you pressed %c \n",key);
   if(key == '0' || key == '1' || key == '2' || key == '3'){
      printf("it's a numeral\n");
   }
   else {
      printf("it's not a numeral\n");
   }
}

Code is not tested. ;-)

The best way in bigger programms is to work with regular expressions.

I hope, this answer was helpful.

shadowdiver
  • 101
  • 1
  • 6
  • 1
    This code's behavior is the same as OP; in what way is it better? – Scott Hunter May 20 '12 at 22:20
  • 1
    @ScottHunter: in the opposite, I see many issues in that answer. Multiple empty cases for a simple common processing is just much simpler that coding a bloated if condition and is the way to do with a `switch`. And the advice concerning general unconditional use of regular expressions is a symptom of the golden hammer syndrome. – Seki May 21 '12 at 09:38
-1
  • the problem might be due to, input buffer not flushing. when "1" is matched in the switch case, a newline character remains in the buffer.
  • try this,
     fflush(stdin)
pritam
  • 2,452
  • 1
  • 21
  • 31