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. }