验证scanf函数输入 [英] Validate input of scanf
本文介绍了验证scanf函数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要阅读时间:在这个确切的格式分钟。我使用的:
I need to read hours:minutes in this exact format. I use:
int hours, minutes;
if (scanf("%d:%d", &hours, &minutes)!= 2)
{
printf("Wrong input.\n");
return 1;
}
else if (minutes>60 || minutes<0 || hours<0)
{
printf("Wrong input.\n");
return 1;
}
time = hours*60 + minutes;
/*read another time interval */
if (scanf("%d:%d", &hours, &minutes)!= 2)
{
printf("Wrong input 2.\n");
return 1;
}
else if (minutes>60 || minutes<0 || hours<0)
{
printf("Wrong input 2.\n");
return 1;
}
...
工作正常,但我需要得到输入错误还的情况下,有人进入如5:38abc
works fine, but I need to get "wrong input" also in situations that someone enters e.g. 5:38abc
推荐答案
运营商加入格式字符串相匹配的新行:
Add an operator to the format string to match the newline:
int hours, minutes;
char str[2];
if (scanf("%d:%d%1[\n]", &hours, &minutes, str)!= 3)
%[\\ N]
匹配换行字符,字段宽度 1
使其停止正好1日后匹配性格。
%[\n]
matches newline characters, and the field width 1
makes it stop matching after exactly 1 character.
这篇关于验证scanf函数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文