通过cin比较c++中的两个数组

Comparing two arrays in C++ through cin

本文关键字:两个 数组 cin 比较 c++ 通过      更新时间:2023-10-16

我试着这样做

string account[3]={"asr123","cbg567","oit777"};
int  pins[3]={1234,4567,7890};
string userAccount;
int userPin;
cin >> userAccount;
cin >> userPin;

现在如何使帐户"asr123"和pin"1234"在一起",即1234是该帐户的pin ?有什么提示吗,我试过了但是这些引脚

您应该使用map来代替,它将易于编码且高效。

map<string, int> passwords;
passwords["asr123"]=12345; // do like this for all pairs
string userAccount;
int userPin;
cin >> userAccount;
cin >> userPin;
if(passwords[userAccount]==userPin){
  cout<<"OK";
}
else{
  cout<<"incorrect";
}

如果要查找具有特定ID的字符串,可以使用std::map。您可以稍后逐个添加字符串对(在您的示例中为3对),然后轻松地使用int查找字符串。

听起来您想要确保用户输入的两个值与您的两个数组中的两个值匹配。

线性时间的解决方案是循环遍历这两个数组,尽管这不是检查用户登录的好方法。

你可以这样写:

for (int i = 0; i < 3; i++) {
    if (userAccount.compare(account[i]) == 0 && userPin == pins[i]) {
        // Do something because there was a match.
    }
}