[C / C ] Check in with scanf string there is some?
Really when this article weigh yourself do not know its title should write how… “Check the number you enter there is some” @@Slightly funny because it's called number and then check what, or is “Check the number of C” – well not quite ready for the purposes of this article. And finally decided to put as above for the purpose of entering into by scanf will know immediately that there is no number or.
The program will perform the following request you to enter an integer (int), If you enter the wrong number (whether any string format “12dabc”, “abc123”, even a real number 12.3) they are caught you in again.
#include <stdio.h> #include <stdlib.h> int clean_stdin() { while (getchar() != 'n') { } return 1; } int main(void) { int input; char c; do { printf("Enter an integer: "); } while (((scanf("%d%c", &input, &c) != 2 || c != 'n') && clean_stdin())); printf("done, number is %d", input); return 0; }
Explain yourself a little:
scanf(“%d%c”, &input, &c)
This will allow us to enter into an integer and a character that immediately follows this integers and it returns an integer value – the number of variables that it receives (sweep) be in accordance with the format in the format string.
– If you enter abc this function returns a value of 0 because it can not be read by a suitable value does.
– If you enter 123 and press Enter the return value is 2 That is 2 accepted value format, 123 Enter the% d and the% c.
– If you enter 123abc and press Enter the return value is 2 That is 2 accepted value format, 123 for% d and% c for a character.
scanf(“%d%c”, &input, &c) != 2 || c != ‘n’
It ensures that the amount of data that is not scanf scan 2 or character received is not enter. Put this condition in the while to the machine can perform properly if you do not have to enter the right number and then enter it will repeat.
(scanf(“%d%c”, &input, &c) != 2 || c != ‘n’) && clean_stdin()
Jaw clean_stdin() the function always returns a value 1 (which is always true) it is the delete buffer villa (stdin) by reading the entire character left in the buffer (scanf characters that can not be read with its input formats) until the reader to enter characters. The conditions put it in a while loop to wipe cache every time you enter in service in again next time.
Posts with reference to the comment in stackoverflow.com
Bài của bạn rất hay. Nhưng có một chổ mình vẫn không rỏ là tại sao lại có điều kiện scanf != 2. Mình thử bỏ nó đi chỉ có c != ‘\n’ thì nó vẫn chạy. Cám ơn vì sự trả lời. 🙂
Hàm scanf sẽ trả về 1 số tương ứng với số lượng biến được nhập vào, do đó mình nhập 2 số thì so sánh với 2
cảm ơn tác giả nhé ^^
Can you explain more about the clean_stdin function operation?() OK
It will clear the input cache.