switch case statement keeps going straight to default option

Posted 19 April 2013 - 12:10 AM

Hi everyone, iv written this code which reads in a kelvin degrees temperature then gives you the option to convert it to either Celsius or Fahrenheit, However my switch case statement for the convert function keeps going straight to the default option and I can't figure out why. I've tried searching around but I can't seem to find an answer specific enough. Can someone please help me? Here is the code:

Re: switch case statement keeps going straight to default option

Posted 19 April 2013 - 11:18 AM

Thanks everyone for the help! It seems my problem was solved by adding in the %*c buffer in the first scanf line but why do I need to do this? Could someone please explain why this is necessary so I don't make the same mistake again? Thank you!

Re: switch case statement keeps going straight to default option

Posted 19 April 2013 - 11:38 AM

Quote

Thanks everyone for the help! It seems my problem was solved by adding in the %*c buffer in the first scanf line but why do I need to do this? Could someone please explain why this is necessary so I don't make the same mistake again? Thank you!

This because the scanf() call leaves the end of line character (the enter key) in the input buffer. So you must extract this character before your next character entry. This is only necessary when dealing with character input, numeric input skips leading whitespace by default. Also note another way or removing this character is to have your character input skip the leading white space as well. You do this by putting a space in front of the character entry:

Re: switch case statement keeps going straight to default option

Posted 19 April 2013 - 11:46 AM

It is absolutely NOT necessary. You have to be aware of what's going on. There are more characters there than you expect, mostly because of hitting enter. You should allow for that by checking for valid characters.

Re: switch case statement keeps going straight to default option

Posted 19 April 2013 - 12:08 PM

Thanks baavgai I understand what your saying, it's just that I wrote the %*c after scanning a character in the second scanf() and left out the %*c for the first scanf() because it was only reading an integer and I didn't think this was necessary, but in doing so this caused my switch case statement to keep going to default until I went back to the first scanf() and put %*c after the %d I just want to understand why that happened?