0

I am totally new to C programming, and now, as I am writing my first program, I have encountered a problem with breaking from a while loop. Here is my code:

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

int multipl(int x, int y);

int main(){
    int x, y, result;
    char replyChar;
    while (1){
        printf("Enter two numbers to be multiplied: \n");
        printf("Number A: "); scanf("%d", &x);
        printf("\nNumber B: "); scanf("%d", &y);

        result = multipl(x, y);
        printf("\nThe product of %d and %d is %d", x, y, result);
        printf("\nDo you wish to proceed?(y/n): ");
        scanf("%c", &replyChar);
        if (replyChar == 'n'){
            printf("Exiting the program.. :)");
            break;
        }
        else{
            continue;
        }
    }
    return 0;
}

int multipl(int x, int y){
    return x * y;
}

The problem is that after function 'multipl' returns a result and the 'Do you wish to proceed' phrase comes on, the code does not wait for receiving the replyChar, and just prints printf("Enter two numbers to be multiplied: \n");. How can I make my code wait for the replyChar without going on further? Thanks in advance for your help!

  • 2
    Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Ret `scanf(" %c", &replyChar);` (added a space). – Weather Vane Dec 09 '22 at 19:04
  • 1
    Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. The reason is those three specifiers allow you to read every character including whitespace, but a way is provided so they behave like `%d` and `%f` and `%s` (etc) where needed. – Weather Vane Dec 09 '22 at 19:06
  • 1
    @WeatherVane , Oh, thank you so much for your explanation! I've now just edited the scanf line as you advised me to, and everything is working as expected now. C language feels somewhat weird after Python, huh. – Stanford Martinez Dec 09 '22 at 19:09
  • 1
    Aside: you don't need `else { continue; }` here because there is nothing more in the loop anyway. – Weather Vane Dec 09 '22 at 19:35

0 Answers0