简体   繁体   中英

Do while loop in C or C++ for multiple inputs

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);


}

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?

while((days<28)||(days>31)); // ie. while days are illegal because to low OR too high

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));

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM