scanf char variable in between scanf integer variable doesn't work?

12,169

Solution 1

You should test that you get a value from scanf(), every time.

The %c character reads the blank or newline after the first number; use " %c" with a leading space to skip over optional white space before reading the character.

if (scanf("%d", &number1) == 1 &&
    scanf(" %c", &a) == 1 &&
    scanf("%d", &number2) == 1)
{
    ...process possibly valid input...
}
else
{
    ...diagnostics...
}

It will probably be easier to give good diagnostics if you read whole lines with fgets() and parse them with sscanf().

  • Recommendation 1: show an example of what you type as input and what you get as output. This makes it easier for people to help you (they can tell whether the program is producing the same output for them).
  • Recommendation 2: echo your input so you can see what the program got. This allows you to tell whether the program got the input you expected. You'd probably find that number2 was not containing what you expected, for example.
  • Recommendation 3: initialize number1 and number2 to -1 so you can see when the scanf() failed (since you aren't yet checking whether scanf() succeeded).

Solution 2

The problem is because of the newline char \n left over by the scanf. This could be avoided by placing a space before format specifier %c.

Try this

scanf(" %c", &a);  
       ^ An space  

this will help you to eat up \n char left over by first scanf

Share:
12,169
JMusicTouch
Author by

JMusicTouch

Updated on October 03, 2022

Comments

  • JMusicTouch
    JMusicTouch over 1 year

    I thought of making a calculator, just a simple one with loops and the basic operations, but the weird thing is that the scanf of character in between my scanf for number is being ignored. It works fine if I put it on top of the scanf of integer but it wouldn't look anything like a calculator. Is there any way to solve this issue? It's not yet finished; got an error up to here, so wondering what's wrong.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
        int number1,number2,total;
        char a;
        printf("This is your personal calculator:(End with ""="")\n");
    
        scanf("%d",&number1);
        scanf("%c",&a);
        scanf("%d",&number2);
    
        if (a == 'x' || a == 'X' || a == '*'){
            total=number1*number2;
            printf("%d",total);
        } else if (a == '/'){
            total=number1/number2;
            printf("%d",total);
        } else if (a == '+'){
            total=number1+number2;
            printf("%d",total);
        } else if (a == '-'){
            total=number1-number2;
            printf("%d",total);
        } else {
            printf("error");
        }
    
        system("pause");
        return 0;
    }