-3

I can't understand why this does exactly what I want. The part where I used two scanf's in the loop confuses me. I compiled it using devcpp.

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

int main()
{
    int dend, dsor, q, r;
    char c;
    while(c!='n')
    {
        printf("enter dividend: ");
        scanf("%d", &dend);
        printf("enter divisor: ");
        scanf("%d", &dsor);
        q=dend/dsor;
        r=dend%dsor;
        printf("quotient is %d\n", q);
        printf("remainder is %d\n", r);
        scanf("%c", &c);
        printf("continue? (y/n)\n");
        scanf("%c", &c);
    }
    system("PAUSE");
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 2
    where is `do...while`? – Sourav Ghosh Oct 21 '16 at 15:32
  • 1
    This is no "explain my code" site. What is your problem? Did you read the man-pages of the functions? – too honest for this site Oct 21 '16 at 15:33
  • 2
    Consider what happened to the trailing newline that remained in the input stream after you finished extracting your *second* number. A debugger and some single-stepping would probably have helped significantly here. – WhozCraig Oct 21 '16 at 15:33
  • Related: The reason why the solution [to this question](http://stackoverflow.com/a/36284545/1322972) (and *hundreds* like it) works is to avoid the otherwise brittle solution you have here. For example, when entering your second number, add a blank space, *then* hit enter on your keyboard and see what happens. – WhozCraig Oct 21 '16 at 15:42
  • 1
    You could and probably should use a single `scanf(" %c", &c);` call after the 'continue' prompt. The leading space reads newlines and leading blanks etc. You should check each and every `scanf()` to ensure you get the correct number of values converted successfully (`if (scanf(…) == 1)` happens to be correct in this code in each case, but you should check for the expected number of values). – Jonathan Leffler Oct 21 '16 at 21:01

1 Answers1

2

FWIW, your code invokes undefined behavior. In the part

char c;
while(c!='n')

c is an uninitialized local variable with automatic storage and you're trying to use the value of c while it is indeterminate.

That said, first scanf("%c", &c); is used to eat up the newline present in the input buffer due to the press of enter key after previous input. You can read about it in details in another post.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261