getchar not working in switch case (c)

╄→尐↘猪︶ㄣ 提交于 2019-12-07 15:47:27

What everyone else here is saying is true, getchar() returns an int but that's not your problem.

The problem is that getchar() leaves a newline character after you use it. If you're going to use getchar() you must always consume the newline char afterwards. This simple fix:

   printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
    c = getchar();
    getchar();     //<-- here we do an extra getchar for the \n
    printf("\tplease enter a number \n");
    scanf("%d",&number[0]);
    printf("\tplease enter another number \n");
    scanf("%d",&number[1]);

and that will eliminate the problem. Every time you type <somechar><enter> it's really putting two characters on the buffer, for example if I hit + and enter I'm getting:

'+''\n'  // [+][\n]

getchar() will only get the first of these, then when getchar() is called again it won't wait for your input it will just take that '\n' and move on to the scanf()

You shouldn't mix character-by-character with more high-level input functions such as scanf(). It's better to use scanf() to input the command character too, but of course then you will have to press enter after the command. I believe this it the root cause of your problems.

As an aside, note that getchar(), despite it's name, returns int, not char. This is because it can return EOF which is a special constant whose value is different from that of all characters.

Further, you should always check the return value of I/O functions like scanf(), they can fail if the input doesn't match the pattern string.

As a debugging hint, you can of course print the value of c before interpreting it, so you can easier see and understand the flow of the program.

I'm guessing it works the first time, but not the next time. This is because the scanf calls leaves the newline in the input buffer so the next time getchar is called in the loop it will return the newline character. Add a space after the format in the scanf calls

scanf("%d ",&number[0]);

and it will discard remaining whitespace from the buffer.

Use a debugger to step through the code and check the variables to verify.

Your getchar should return int. The reason is as below

getchar reads characters from the program's standard input 
and returns an int value suitable for storing into a char. 
The int value is for one reason only: not only does getchar 
return all possible character values, but it also returns an 
extra value to indicate that end-of-input has been seen. 
The range of a char might not be enough to hold this extra value, 
so the int has to be used.

So basically you need to change char c to int c in your code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!