How to stop a while loop

前端 未结 5 1855
醉梦人生
醉梦人生 2021-01-14 14:41

This while loop never ends. For example, when i enter a wrong password it will keep on going to the \"incorrect password\" part over and over again.

Logo();
         


        
5条回答
  •  庸人自扰
    2021-01-14 14:47

    First, read the correct usernames and passwords from the file and save them in memory. That way, if the username/password validation fails the first time, you don't have to reopen or seek-to-beginning-in the file before checking on the next username/password typed by the user....

    std::map usernames_passwords; std::string username, password;

    if (ifstream in("UsernamePassword.txt"))
        while (in >> username >> password)
            usernames_passwords[username] = password;
    else
    {
        std::cerr << "Unable to open username/password file\n";
        exit(EXIT_FAILURE);
    }
    

    Then prompt for login details until they're valid:

    bool logged_in = false;
    while (!logged_in &&
           std::cout << "\n\n\n    Please enter username: " &&
           std::cin >> username &&
           std::cout << "    Please enter password: " &&
           std::cin >> password)
    {
        // look for a match in the earlier-read login details...
        auto it = usernames_passwords.find(username);
        logged_in = it != std::end(usernames_passwords) && it->second == password;
    }
    
    // the while loop could also exit because "cin >>" failed, indicating EOF
    // that could be because the user typed e.g. ^D (UNIX) or ^Z (Windows), or
    // input was from a redirected file or pipe or over a network connection...
    
    if (!logged_in)
    {
        std::cerr << "error reading login details from stdin\n";
        exit(EXIT_FAILURE);
    }
    
    ...ok - we know the username/password are good - do whatever else...
    

提交回复
热议问题