使用while循环在C中进行数据验证

时间:2017-03-05 19:36:06

标签: c validation

#include<stdio.h>
main()
{
    char status;
    printf("STATUS     SYMBOL\n");
    printf("------     ------\n");
    printf("Senior        s\n");
    printf("Junior        j\n");    
    while(1)
    {       
        printf("Please Enter the Salesperson's Status : ");
        scanf("%c",&status);
        if (status=='s' || status=='j')
        {
            if(status=='s')
            {
                printf("Weekly Salary is --- $400\n");
                break;
            }
            else
            {   
                printf("Weekly Salary is --- $275\n");
                break;
            }
        }
        else
        {
            printf("Please Enter a Valid Symbol!\n");

        }
    }
}

当输入无效数据时,该程序必须向用户询问有效数据。While循环用于验证数据执行两次,以便询问用户输入。为什么在First-Go上忽略scanf功能?如何解决这个问题呢? Program Output

1 个答案:

答案 0 :(得分:0)

因为键入a<ENTER>时键入2个字符。 所以第一个scanf得到a,第二个得到\n(ENTER)。

您可以将scanf更改为2个字符而不是1个字符。

scanf("%c%c", &status, &newline);