C 文件输入流循环问题



在C 程序上工作。想要制作一个用户名"检查器"。在一段时间内处理ifstream。我遇到的问题是,如果不存在用户名,那么它每次都在文本中打印错误消息。我知道问题是在循环中。我不知道如何在不检查用户名的文件的情况下提供错误消息。任何帮助将不胜感激。谢谢!

string username;
string password;
int input;
bool keepGoing;
while (keepGoing){
cout<<("1.Loginn2.Create Username and Passwordn3.Exit")<<endl;

cin>>input;
///////////////////////////////////////////////////////////
        if(input == 1){ //LOGIN!!!
        //open the file
        ifstream user("userinfo.txt");
    if(user.is_open()){
    //get the username
    string checkUser;
    string checkPass;
    cout<<"Enter username: "<<endl;
    cin>>checkUser;
    //create a variable to store existing username
    //Iterate throught the text file, and log them in if thier info is correct
    //while(user>>username>>password){
    while(getline(user, username)){
        //if the name is there
        if (checkUser != username){
            cout<<"Username not here!"<<endl;
        }
        if (checkUser==username){
            //cout<<"Welcome back, "<<username<<endl;
            cout<<"Password: "<<endl;
            cin>>checkPass;//get user input
                if(checkPass==password){//if the password is correct
                    cout<<"Welcome back, "<<username<<endl;//User is logged in
                    //put in the menu 2 function
                }else if(checkPass!=password){//If pass is incorrect
                    cout<<"Password incorrect."<<endl;//Denied
                }//end else if
            }//end if
    }//end while loop
   }
   else{
    cout<<"Unable to open file"<<endl;
     }
    }

只是这样做

bool foundUser = false;
while(getline(user, username)) {
    if(checkUser == username) {
        foundUser = true;
        break;
    }
}
if(foundUser) {
    // check password here
}
else {
    // display error message
}

您应该将检查用户名的逻辑提取到一个函数中,该函数将在sucsses上返回true,false在失败上。

bool checkUser(const std::string& username, const std::string& pass){
//check if user exists
while(getline()){
if(username == somthing)
{
    if(pass == somthing){
       return true;
    }
    std::cout << "incorrect pass";
    return false;
}
}
//if you reached here than the username doesnt exists
return false;
}

最新更新