1

I am a beginner in C and am currently going through the book "C: Einfuehrung und professionelle Anwendung" by Mr. Prinz. The example from the book below should show how to limit the input using scanf and to flush the buffer in between in order to get a new input.

In both cases I enter "123123123123" for the bank account number. If I exit in line 11, then the printf verifies that only the first 8 symbols were stored. If I do not exit in the line 11, then the remaining symbols are written into the "money" field and the programs does not ask for a second input.

I looked through the man pages and know that the locals are allocated on the stack. But I still cannot understand why the overflow happens, or why the example from the book does not work for me. Could you please explain that to a beginner?

Here one says that fflush(stdin) is additionally a coding error. If so, could you please explain why this stands in a book? :)

1. # include <stdio.h>
2. 
3. int main() {
4.     long bank_account;
5.     double money;
6. 
7.     printf("\nEnter your bank account: ");
8.     scanf("%8ld", &bank_account);
9.     printf("Bank account: %d, Amount: %.3f\n", bank_account, money);
10.     
11.     // <- here
12.    fflush(stdin);
13.    
14.    printf("\nHow much money to hold: ");
15.    scanf("%lf", &money);
16.    printf("Bank account: %d, Amount: %.3f\n", bank_account, money);
17.
18.    return 0;
19. }

jupiter_jazz
  • 333
  • 2
  • 8
  • 1
    It's not an overflow as such, it's simply that the remaining symbols are still in the buffer. See https://stackoverflow.com/a/49265365/1871033 for solution. – CherryDT Nov 02 '21 at 10:23
  • Please post your code without line numbers next time. – Jabberwocky Nov 02 '21 at 10:23
  • 1
    I recommend that you *don't* use integers for account, phone, card, house etc numbers. Use a string. If the account number entered was longer than 8, don't truncate it (as your `scanf` usage would) but flag it as incorrect entry, without giving the user any clue why. – Weather Vane Nov 02 '21 at 10:23
  • 2
    As for why the incorrect fflush is taught in the book: it is apparently not the best book, and it seems it teaches things that happen to work on the author's platform but won't work universally (as you discovered - it's not working on _yours_) – CherryDT Nov 02 '21 at 10:26
  • 1
    `fflush(stdin)` was supported by Windows, in early compiler versions, but not now. – Weather Vane Nov 02 '21 at 10:26
  • thank you! Both suggestions were very helpful! – jupiter_jazz Nov 02 '21 at 10:43

1 Answers1

2

Your bank account is long type - so your printf should use %ld instead:

printf("Bank account: %ld, Amount: %.3f\n", bank_account, money);
artm
  • 17,291
  • 6
  • 38
  • 54