0

I'm a total C noob and i had quite a similar question about scanf which was answered and again, I came here out of total desperation. Every question i read about here (about scanf before gets) was answered in "put an extra space after %d for example" and it works here:

    int month,day;char waste[10];
    printf("Enter month: ");scanf("%d",&month);
    printf("Enter day: ");scanf("%d ",&day);
    //printf("break!");
    gets(waste);
    printf("month: %d, day: %d\n",month,day);
    puts(waste);

but if the "//printf("break!");" line gets uncommented, something strange happens! first the first three lines run and you have to enter the two scanfs, but after the second scanf, " gets(waste) " runs AND THEN the " printf("break!") " IN THE LINE BEFORE IT! here's the code from my terminal.

Enter month: 11
Enter day: 2
sssd
break!month: 11, day: 2
sssd

That's some paranormal ish to me. how do you think I can fix this?

rezzyrezz
  • 21
  • 2
  • 3
    Out of curiosity, did those same questions that suspiciously told you to "put an extra space after %d for example" mention anything about the questionable sanity of using `gets`, a function so vile and evil it has been removed from the standard library, in the first place? Regardless, `fflush(stdout);` seems to be on the menu. – WhozCraig Jan 30 '20 at 21:06
  • Do you know what that space does? (The `gets()` (**never use that function!**) doesn't run before the `printf()` btw. Understanding that space and the concept of buffering will help you understand). – Shawn Jan 30 '20 at 21:13
  • 1
    When you put space in the format string, it skips over all whitespace. But it doesn't know when has reached the end of the whitespace until it gets something that *isn't* whitespace. So it has to wait for you to type a non-blank line. – Barmar Jan 30 '20 at 21:16
  • 1
    1. Do not use `gets`. Ever. Not even in toy code. It was removed from the standard library in the 2011 standard, and it *will* introduce a point of failure in your code. Use `fgets(waste, sizeof waste, stdin)` instead. 2. Do not mix calls to `scanf` and `fgets`. 3. Do not add trailing whitespace to your conversion specifications in `scanf`. – John Bode Jan 30 '20 at 21:24
  • I have three basic rules of C programming: Don't use `gets`. Don't use `scanf` with `gets`. Don't use `scanf`. – S.S. Anne Jan 30 '20 at 21:32
  • @S.S.Anne that could be optimized to 2 rules – M.M Jan 30 '20 at 22:12
  • @M.M Yes it could. But I think the compiler should be able to optimize it out for me. – S.S. Anne Jan 30 '20 at 22:13

0 Answers0