在C中验证正确的月份

时间:2014-02-17 20:41:24

标签: c

我在这个程序中工作很容易,但是我在验证输入用户时遇到了问题,我不知道如何从用户那里获得正确的输出。该计划说要获得上次换油的日期(月份和年份)。   执行输入验证并在输入不正确时请求用户输入正确的值。 这就是我到目前为止所做的,而且我不知道到目前为止我所得到的是否正确:

#include <stdio.h>

int main(void)
{
    int month, year;

    // Enter the date of last oil change and Validate the correct month value

    printf("Enter the Date of last oil change, month (1-12): ");
    scanf("%i", &month);

    if (month > 0 && month <= 12)
    {
        printf("Month: %i\n ", month );
    }
    else
    {
        printf( "Please enter a number between 1-12.\n " );
    }

    return(0);
}

2 个答案:

答案 0 :(得分:1)

尝试这样做:

int main(void)
{
int month, year;

// Enter the date of last oil change and Validate the correct month value

printf("Enter the Date of last oil change, month (1-12): ");
//Add a space before %i to disregard whitespace.
scanf(" %i", &month);

while (month < 1 || month > 12)
    {
        printf( "Please enter a number between 1-12.\n " );
        scanf(" %i", &month);
    }

printf("Month: %i\n ", month );

return(0);
}

这样,程序会一直询问用户一个值,直到输入正确的值为止。

答案 1 :(得分:1)

这个想法是不断向用户询问年份和月份的正确值,这是实现这一目标的一种方法:

#include <stdio.h>

int main(void)
{
    int month = 0;
            int year = 0;
    // Enter the date of last oil change and Validate the correct month value

    printf("Enter the Date of last oil change, month (1-12): ");
    scanf("%d", &month);

    while(month <= 0 || month > 12) { //loop until the values are correct
        printf("Please enter a number between 1-12: \n");
        scanf("%d", &month);
    }

    printf("Enter the Year of last oil change:");
    scanf("%d", &year);

    while(year <= 0) { //same here (the years must be positive)
        printf("Please enter a positive number to be a year\n");
        scanf("%d", &year);
    }

    return 0;
}