Reputation: 45
I am working in this program which is very easy but I am having trouble validating the input user, I do not know how to get the correct output from the user. The program says to get the date of last oil change (month and year). Perform input validation and request the user enter correct values when input is incorrect. This is what I have so far, and I don`t know if what I got so far is correct:
#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);
}
Upvotes: 1
Views: 248
Reputation: 901
The idea is keep asking to the user for the correct value of year and month, this is a way to achieve that:
#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;
}
Upvotes: 1
Reputation: 2846
Try doing it like this instead:
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);
}
This way the program keeps asking the user for a value until a correct one is entered.
Upvotes: 1