2017-06-27 136 views
-5

我正在写一个程序(主要是教育目的,但如果我喜欢它,那么我可能会在稍后使用它在更大的项目中)进行用户名和密码验证。到目前为止,我的工作“有效”,这意味着没有错误,但它确实有点奇怪。它在退出之前做了大约9次(我没有保存确切的输出)的STUFF(),它只是一次完成。用户名和密码检查

我该如何让它做一次STUFF()?我怎样才能使密码输入不可见?我怎样才能普遍提高安全性/语法或缩短?

#include <iostream> 
using namespace std; 

void STUFF() 
{ 
    cout << "Doing stuff..." << endl; 
} 

int CREDS; 
void AUTH() 
{ 
    cout << "Username: "; string USER; cin >> USER; 
    cout << "Password: "; string PASS; cin >> PASS; 
    if (USER == "josh" and PASS == "passwd") 
    { 
     CREDS = 0; 
    } 
    else 
    { 
     CREDS = 1; 
    }; 
} 

void RETRY() 
{ 
    cout << "Authentication failed! Try again? [Y/n]" << endl; char REPLY; cin >> REPLY; 
    if (REPLY == 'Y' or REPLY == 'y') 
    { 
     AUTH(); 
    } 
    else if (REPLY == 'N' or REPLY == 'n') 
    { 
     cout << "Exiting..." << endl; 
    } 
    else 
    { 
     RETRY(); 
    }; 
} 

int main() 
{ 
    AUTH(); 
    if (CREDS == 0) 
    { 
     STUFF(); 
     return 0; 
    } 
    else if (CREDS == 1) 
    { 
     RETRY(); 
    }; 

} 
+0

不能重现:https://ideone.com/EPnGn4 – mascoj

+0

此外,您的RETRY代码不会按照您的预期行事。即使输入“Y”,程序也不会退回。 – mascoj

+0

我再次测试(使其成为获取用户并传递错误的重试点)。选择不退出并选择是,然后让他们正确退出而不做任何事情。编辑:再次复制结果两次然后得到用户/第一次传递正确,并打印“auth失败!再试一次?”正好9次 – Josh

回答

0

我已经放弃了最后的程序,并从头开始写这个。 对于任何想使用C++的人来说,它都是GNU GPLv2授权的,可以在Github的Small-Projects-Cpp找到。只需下载“Userpass.zip”,因为它不需要克隆整个存储库。

#include <iostream> 
#include <string> 
#include <unistd.h> 
#include <termios.h> 

getpass()使密码输入显示星号。不完全看不见,但它可能是最好的解决方案。菜单()有一个开关/外壳菜单,但它是不相关的,所以我跳过它在asnwer。你可以用你想要的任何功能替换它。

int attempts = 0; 
int main() 
{ 

    while (attempts == 3) 
    { 
     cout << "Too many attempts have been made! Exiting..." << endl; exit(0); 
    }; 
    string USER; 
    cout << "Username: "; cin >> USER; 

    if (USER == "josh") 
     { 
      if (getPASS() == "hsoj") 
     { 
     cout << "\nAccess granted!\n" << endl; 
     MENU(); 
     } 
      else 
     { 
      cout << "\nAccess denied!\n" << endl; 
     attempts = attempts + 1; 
     main(); 
     }; 
    } 
    else 
    { 
     cout << "\nAccess denied!\n" << endl; 
     attempts = attempts + 1; 
     main(); 
    }; 
    return 0; 
}