简体   繁体   中英

If statement doesn't give cout after the first attempt

Why does the if statement not produce the cout after the first attempt, not sure what is happening here, how can i get this loop to work?

srand(time(0) );
int random = rand();
int pswd = (random);

std::cout << pswd << endl;

int pswdattempt;
std::cin >> pswdattempt;


while (pswdattempt != pswd) {
    if (pswdattempt == pswd) {
        std::cout << "Access Granted" << endl;
    }
    else {
        std::cin >> pswdattempt;

    }

assuming you close the while in the full script, and that this is within a function otherwise srand is unlikely to work.

notice if input is correct on first input (before the loop) it will be explicitly excluded by while (pswdattempt != pswd) .

likewise, if the correct integer is given at the prompt in the loop, then the loop will not restart, so the if (pswdattempt == pswd) will still not be reached.

essentially you need a flow that prompts for input, then tries the condition, returning to the prompt if unmet, else exiting the loop to continue granting access or dispensing chocolate if met correctly.

(edit) if cout still produces nothing, i'm a little out of depth here, but i see you havn't set use namespace std; globally so perhaps each endl; should be std::endl;

I see two problems with your code. First is that the rand() function generates a pseudo random number between 0 and some fairly large number, typically at least 32K. This means that you might be sitting there for a while waiting to guess the right number. For testing purposes, try generating a number between 0 and 10. Then, break out of the while loop on a correct guess:

srand(time(0) );
int random = rand() % 10;
int pswd = (random);

std::cout << pswd << endl;

int pswdattempt;

do {
    std::cout << "Please enter a password";
    std::cin >> pswdattempt;

    if (pswdattempt == pswd) {
        std::cout << "Access Granted" << endl;
        break;
    }
} while (true);

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