3

ユーザー名とパスワードを含む auth.txt ファイルがあります。私の目的は、このファイルを使用して、ユーザーが次のメニューに進む前に有効なユーザー名とパスワードを入力したかどうかを確認することです。例えば。auth.txt には、\n ユーザー パスが含まれています。メニューを選択すると、ログオンを求められます。彼らが間違って入力した場合、それは何もしません。各パスワードと usrname は auth.txt ファイルに保存されます。次のコードを使用してみましたが、何も得られませんでした。助けてください、事前に感謝します。

if(getline(inauth, line)){ 

    if(line==user&& line==password){ 
    //your in

    }else cout<<"bye";
    }
4

3 に答える 3

1

私は VC++ 開発者ではありませんが、これは目的を達成するための適切なロジックであるはずです。

// keep looping while we read lines
while (getline(inauth, line)) 
{
    // valid user
    if (line == user) 
    {
        // read the next line
        if (getline(inauth, line2))
        {
            if (line2 == password)
            {
                // successfully authenticated
                cout << "Success!";
            } 
            else 
            {
                // valid user, invalid password
                // break out of the while loop
                break;
            }
        }
    }
}
于 2012-05-12T14:28:47.200 に答える
0

ユーザー名とパスワードが空白などで区切られた同じ行に保存されている場合は、次のことを行う必要があります。

#include <sstream>

string line, username, password;
istringstream instream;
while (getline(inauth, line))
{
    // extract username and password from line using stringstream
    instream.clear();
    instream.str(line);
    instream >> username >> password;
    // do something here
}
于 2012-05-12T14:41:21.330 に答える
0

1行しか読んでおらず、「ユーザー」と「パスワード」の両方と比較しようとしています。それは確かにうまくいきません。getline を 2 回呼び出す必要があります。エラーを確認することを忘れないでください。ユーザー認証で安全になりすぎることは決してありません。次のようなことを試してください:

ifstream inauth("Secret password herein.txt");

if (inauth) {
    string usr, psw;

    if (getline(inauth, usr) && getline(inauth, psw) {
        if (usr == user && psw == password) {
            cout << "Phew, everything's fine.";
        } else {
            cout << "Wrong password/username.";
        }
    } else {
        cout << "I guess somebody opened the file in notepad and messed it up."
    }
} else {
    cout << "Can't open file, sorry.";
}
于 2012-05-12T14:34:31.223 に答える