Reputation: 65
Following is the code snippet i'm working, although I need 4 values for my input, until the user types correct value, it should keep asking, any inputs on the same Thanks in advance
#include<stdio.h>
#include<math.h>
int
main(int argc, char *argv[])
{
int days;
float peny;
do{
printf("Enter Number of days: ");
scanf("%d", &days);
}
while ((days != 28) || (days != 29) ||(days != 30) ||(days != 31));
printf("Number of days are %d", days);
}
Upvotes: 1
Views: 3812
Reputation: 21
The condition
(((days != 28) || (days != 29) ||(days != 30) ||(days != 31)))
in your do-while
loop will always be true because the value of days can not be 28, 29,30, 31 at the same time. The or operator could be changed to and:
while ((days != 28) && (days != 29) && (days != 30) && (days != 31));
Upvotes: 2
Reputation: 24887
while((days<28)||(days>31)); // ie. while days are illegal because to low OR too high
Upvotes: 2
Reputation: 272657
Think about what your loop condition is saying. It will keep looping whilst any of those individual conditions is still true, or to put it another way, looping until all of them are false simultaneously. Is that possible?
Upvotes: 5
Reputation: 754470
Always test the return status from scanf()
; if it doesn't tell you 1, it is failing, perhaps because the user typed a
instead of 31
.
Consider counting the number of consecutive failures (and bailing out if the count gets too high) so the user doesn't get frustrated.
Consider using fgets()
to read the input and sscanf()
to parse it; it is generally easier to manage.
Consider using C++ for C++ and C for C; what you show is a C program rather than a C++ program (though it can indeed be compiled with C++, unless my eyes are deceiving me). In general, the languages are very different.
Include a newline at the end of the final printf()
.
Upvotes: 1