How to stop a while loop

前端 未结 5 1874
醉梦人生
醉梦人生 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:57

    It keeps on an infinite loop because you never ask if you reached the end of the file, so, if the file does not contain a username/password combination that matches the pair entered by the user, when the end of the file is reached, the line:

    inFile >> username >> password; 
    

    Fails and username and password will contain the last entries seen on UsernamePassword.txt and the loop goes forever.

    The following implementation of your program will test for the eof in the inFile file object:

    #include 
    #include 
    #include 
    #include 
    int main() { 
        std::ifstream inFile;    
    
        std::string user, pass;
        std::string username, password;
    
        inFile.open("UsernamePassword.txt");
        if (!inFile) {
            std::cout << "Unable to Open File";
        } else {
            std::cout << std::endl << std::endl << std::endl;
            std::cout << "           Please enter username: ";
            std::cin >> user;
            std::cout << "           Please enter password: ";
            std::cin >> pass;
    
            while (username != user && !inFile.eof()) {
                inFile >> username >> password;
    
                if (user == username && pass == password) {
                    std::cout << std::endl;
                    std::cout << "Welcome to CherryLunch!" << std::endl;
    
                    // Equivalent to the 'pause' command in linux
                    system("read -p 'Press any key to continue...' key");
                    // Equivalent to the 'cls' command in linux
                    system("clear");
    
                    // MainMenu();
                } else {           
                    std::cout << std::endl;
                    std::cout << "           Invalid Username or Password!" << std::endl << std::endl;
    
                    system("read -p 'Press any key to continue...' key");
                    system("clear");
                }
            }
        }
        inFile.close(); 
    }
    

提交回复
热议问题