0

My code isn't asking for the second %c input and just printing the result. of the first and printing the next question after.

This is the assignment: Students can take Programming module if they are from SOE or they have passed Math. Otherwise, they cannot take the module. Write a program to allow students to check their eligibility. Your program must have only one if-else statement and must use the OR logical operator in the condition. Your program must be able to produce the sample outputs given below. Note that the values underlined are the input data.

this is the code i wrote:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char soe, math;
    
    printf("Are you from SOE [y/n]? ");
    scanf("%c", &soe);
    
    printf("Did you pass Math [y/n]? ");
    scanf("%c", &math);
    
    if(soe == 'y' || math == 'y'){
        printf("OK, you can take Programming");
    }
    
    else{
        printf("Sorry, you cannot take Programming");
    }
}
Are you from SOE [y/n]? y
Did you pass Math [y/n]? OK, you can take Programming

it immediately prints the 2nd printf after the 1st input and doesnt ask for a second input

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
rewed
  • 61
  • 1
  • You pressed two keys 'y' and 'enter'. – stark Apr 30 '22 at 13:28
  • In future, please post the output as text, not as an image. See this link for the reason: [Why not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/q/285551/12149471) Meanwhile, I have fixed it for you. – Andreas Wenzel Apr 30 '22 at 13:58

1 Answers1

1

You have to use getchar() between two scanf function calls, unless they are using the %d conversion format specifier. (This function cleans the buffer by consuming the ENTER key that you pressed after the first scanf. If you don't do it, the ENTER key still exists and the next scanf will take it as an answer.)

This way :

    printf("Are you from SOE [y/n]? ");
    scanf("%c", &soe);
    
    getchar();

    printf("Did you pass Math [y/n]? ");
    scanf("%c", &math);
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Quibble
  • 9
  • 2
  • As I said, your answer is stored in the buffer including the enter key. If you don't delete it and ask for a second answer, the program will read the buffer and found that enter key, and take it as an answer. – Quibble Apr 30 '22 at 13:38
  • Note that `%d` is not the only `scanf` conversion format specifier that consumes leading [whitespace](https://en.wikipedia.org/wiki/Whitespace_character). All specifiers do that, except for `%[]`, `%c` and `%n`. See [this documentation](https://en.cppreference.com/w/c/io/fscanf) for further information. – Andreas Wenzel Apr 30 '22 at 13:46