2016-12-05 61 views
0

使用C++程序。想製作一個用戶名「checker」。在while循環中處理ifstream。我遇到的問題是,如果用戶名不存在,那麼它將每次打印錯誤消息以獲取文本中的行數。我知道問題出在while循環中。我不知道如何在沒有檢查文件的用戶名的情況下給出錯誤信息。任何幫助將不勝感激。謝謝!C++文件輸入流循環問題

string username; 
string password; 
int input; 

bool keepGoing; 
while (keepGoing){ 

cout<<("1.Login\n2.Create Username and Password\n3.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; 

    } 
    } 

回答

2

只是做了這樣的

bool foundUser = false; 
while(getline(user, username)) { 

    if(checkUser == username) { 
     foundUser = true; 
     break; 
    } 
} 
if(foundUser) { 
    // check password here 
} 
else { 
    // display error message 
} 
1

你應該提取檢查用戶名的,其會回報sucsses真假失敗的函數的邏輯。

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