Bart g
Bart g

Reputation: 585

Switch small prgram does not let me input option

I am learning C and I was practicing the switch and I run the program but does not let me input *, +, -, here is my code. I can input 1st and 2th number but not the operator, after I input the numbers the program finishes. Not sure why. Thank you

#include <stdio.h>

int main(int argc, char *argv[])
{
int num1, num2, ans=0;
char ch, name;

printf("Enter a value: ");
scanf("%d",&num1);

printf("Enter a second value: ");
scanf("%d",&num2);

printf("Input * To multiply\
              + To add\
              - To subtract");
scanf("%c",&ch);

switch(ch)
{
case'*':
    ans=num1 * num2;
    printf("%d times %i equals: %i",num1,num2,ans);
    break;

case'+':
    ans=num1+num2;
    printf("%i plus %i equals: %d",num1,num2,ans);
    break;

case'-':
    ans=num1-num2;
    printf("%d minus %d equals: %d",num1,num2,ans);
    break;

default:
    printf("Range numbers");
}
return 0;
}

Upvotes: 0

Views: 125

Answers (2)

hmjd
hmjd

Reputation: 121971

This:

scanf("%c",&ch);

is reading the newline character from the entry of num2: you need to skip it before reading ch.

Change to:

scanf(" %c", &ch);

Adding the space before the %c instructs scanf to skip newlines and whitespace.

Upvotes: 2

Dolda2000
Dolda2000

Reputation: 25855

It is because the scanf("%d") you use is not a line-oriented function. It only reads the number, but leaves the newline character in the buffer, which is then read by the scanf("%c") call.

Since you want to do line-based input, you will probably want to use fgets and atoi instead, to get more well-defined and consistent behavior. The fgets function always reads exactly a line. For example, like this:

char buf[1024];

printf("Enter a value: ");
fgets(buf, sizeof(buf), stdin);
num1 = atoi(buf);

/* ... */

printf("Enter operator: ");
fgets(buf, sizeof(buf), stdin);
ch = buf[0];

Upvotes: 1

Related Questions