linux - Why is scanf() causing infinite loop in Linux ? - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
Why is scanf() causing infinite loop in Linux ?
Linux - Solution 1:
- scanf consumes only the input that matches the format string, returning the number of characters consumed.
- Any character that doesn't match the format string causes it to stop scanning and leaves the invalid character still in the buffer.
- As others said, you still need to flush the invalid character out of the buffer before you proceed.
Linux - Solution 2:
On some platforms (especially Windows and Linux) you can use fflush(stdin);:
Linux - Solution 3:
- scanf() leaves the "a" still in the input buffer for next time. You should probably use getline() to read a line no matter what and then parse it with strtol() or similar instead.
Linux - Solution 4:
Linux - Solution 5:
Rather than using scanf() and have to deal with the buffer having invalid character, use fgets() and sscanf().