我要检查有效输入吗? [英] Hw do I check for valid input?

查看:71
本文介绍了我要检查有效输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查输入是否采用时间格式HH:MM。有效时间为00:00至23:59。我做了:

 printf( 请输入你的年龄:); 
scanf( %f,& age);
if (age < 18
{
printf( 太年轻了,我们无法为你服务。 \
);
return 1 ;
}





 printf( 请以HH:MM格式输入时间:); 
scanf( %c%c%c%c%c,& h1 ,& h2,&冒号,& m1,& m2);
if ((h1< ' 0 ' || h1> ' 2')||(h2< ' 0' || h2> ' < span class =code-string> 9')||(m1< ' 0' || m1> ' 5')||(m2< ' 0' || m2> ' 9'))
{
if (h1 == ' 2'&& h2> ' 3'
{
printf( 时间不是HH:MM格式。);
return 1 ;
}
}



但它不起作用。

解决方案

< pre lang =c ++> if (h1 == ' 2'&& h2大于' 3'



如果任何字符无效,此时此测试是多余的。它应该是初始 if 语句的一部分。类似于:

  if ((h1< '   0' || h1> '  2')||(h2< '  0' || h2> < span class =code-string>'  9')||(m1< '  0' || m1> '  5' )||(m2< '  0' || m2> '  9')||(h1 == '  2'&& h2> '  3' ))
{
printf( 时间格式不是HH:MM。);
return 1 ;
}


I want to check if the input is in the time format HH:MM. Valid time is from 00:00 to 23:59. I did:

printf("Please enter you age: ");
scanf("%f", &age);
if (age < 18) 
{
    printf("Too young, we can't serve you.\n");
    return 1;
}



printf("Please enter the time in the format HH:MM: ");
scanf("%c%c%c%c%c", &h1, &h2, &colon, &m1, &m2);
if ((h1 < '0' || h1 > '2') || (h2 < '0' || h2 > '9') || (m1 < '0' || m1 > '5') || (m2 < '0' || m2 > '9')) 
{
    if (h1 == '2' && h2 > '3')
    {
            printf("The time is not in the format HH:MM.");
            return 1;
    }
}


but it doesn't work.

解决方案

if (h1 == '2' && h2 greater than '3')


If any character is invalid, this test is redundant at this point. It should be part of the initial if statement. Something like:

if ((h1 < '0' || h1 > '2') || (h2 < '0' || h2 > '9') || (m1 < '0' || m1 > '5') || (m2 < '0' || m2 > '9') || (h1 == '2' && h2 > '3'))
{
        printf("The time is not in the format HH:MM.");
        return 1;
}


这篇关于我要检查有效输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆