Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5391

General • Re: C program, flush input, scanf(), menus, etc.

$
0
0
A well known gotcha with scanf() on any platform is that if you request an integer, like scanf(%i, &num); and the user enters a non-numeric character, the program will go into an infinite loop.
No. Only if the program tries the same conversion again, without consuming the bad byte first.
Methods of clearing the input buffer by consuming characters until a newline or EOF is reached do not seem to work on the Pico.

Is there a better way, getchar() maybe?
getchar is a method of consuming input, and it should work. Have you been mixing lower-level methods?

In order to determine that X is not a digit, say, scanf has to have already read it. So that your program can read it again and print "Bad integer: X", scanf puts the X back, using the equivalent of ungetc(). This only puts the character back into the stdio buffer; it cannot give it back to the OS, or stuff it back up the UART.

Yes, there are known dangers with mixing C stdio calls and low-level interfaces such as Linux' read()/write() or Pico's uart_*().

Statistics: Posted by jojopi — Thu Apr 04, 2024 6:28 am



Viewing all articles
Browse latest Browse all 5391

Trending Articles