我正在尝试构建一个简单的身份验证机制,用户输入他的登录凭据,然后将他的输入与文件'UserDB.txt'中的内容进行比较。但是,当我尝试遍历文件并将其凭据与文件中的所有行进行比较时,会发生以下错误:
main.cpp:86:38: error: could not convert ‘credential.std::basic_string<_CharT, _Traits, _Alloc>::operator=<char, std::char_traits<char>, std::allocator<char> >((*(const std::basic_string<char>*)str.std::vector<_Tp, _Alloc>::operator[]<std::basic_string<char>, std::allocator<std::basic_string<char> > >(((std::vector<std::basic_string<char> >::size_type)i))))’ from ‘std::basic_string<char>’ to ‘bool’
这是我的代码:
std::cout << "\nEnter Username: " << endl;
std::getline(std::cin,username);
std::cout << "\nEnter password: " << endl;
std::getline(std::cin,password);
credential=username + ":" + password; //Concatenates the credentials into one variable
std::fstream myFile("UserDB.txt");
if (myFile.is_open())
{
std::istream_iterator<std::string> iter(myFile), end;
std::vector<std::string> str(iter, end);
// print contents
for (int i = 0; i < str.size(); i++)
{
std::cout << i << ": " << str[i] << std::endl;
if (credential=str[i]) //Error occurs here
{
cout << "Credentials accepted!" << endl;
}
else
{
cout << "Login fail! Wrong credentials..." << endl;
exit(0);
}
}
}
我知道我可能不应该在g ++中使用-fpermissive标志,因为它可能会回来并在后面咬我的屁股。那么我该如何避免这个问题?
答案 0 :(得分:2)
您应该将credential=str[i]
更改为credential==str[i]
。你需要double =或者它会尝试将credentials
设置为等于str[i]
答案 1 :(得分:0)
没问题我找到了解决方法......
std::cout << "\nEnter Username: " << endl;
std::getline(std::cin,username);
std::cout << "\nEnter password: " << endl;
std::getline(std::cin,password);
credential=username + ":" + password; //Concatenates the credentials into one variable
std::cout << "Variable credential is :" + credential;
string array[50]; // creates array to hold names
short loop=0; //short for loop for input
string line; //this will contain the data read from the file
ifstream myfile ("UserDB.txt"); //opening the file.
if (myfile.is_open()) //if the file is open
{
while (! myfile.eof() ) //while the end of file is NOT reached
{
getline (myfile,line); //get one line from the file
array[loop] = line;
//cout << "\n";
//cout << loop << ":" << array[loop] << endl; //and output it
if (credential==array[loop])
{
cout << "Login successful!";
displayMenu();
}
else
{
//Login failed...
loop++;
}
}
myfile.close(); //closing the file
}
else cout << "Unable to open file"; //if the file is not open output