[英]How do I check if a binary number, provided by continuous user input, is divisible by 5 each time a digit is entered?
[英]How to check if user entered an input or not
我使用此代碼來允許為變量輸入數值:
float day;
printf("Day?: ");
scanf("%f",&day);
如果用戶未為“天”輸入任何值,我如何使程序產生錯誤消息?
嘗試這個:
if(scanf("%f",&day) != 1)
printf("Error");
使用fgets()/sscanf()
char buf[100];
fgets(buf, sizeof(buf), stdin);
if (sscanf(buf, "%f", &day) != 1) {
if (buf[0] == '\n')
HandleNothingInput();
else
HandleBadInput();
}
}
fgets()
通常讀取直到輸入Enter或'\\n'
。 通過使用sscanf()
解析緩沖區,很容易檢測到空輸入(“用戶未輸入ANY值”),錯誤輸入(“ abc”),因為scanf()
的結果將為0。
替代方法:如果要確保沒有輸入其他數據,可以使用一個哨兵:
int ch;
if (sscanf(buf, "%f %c", &day, &ch) != 1) {
atof()
是另一種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.