C++ - 无法从 std::基本字符串<char>转换为布尔值



我正在尝试构建一个简单的身份验证机制,用户输入他的登录凭据,然后将他的输入与文件'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标志,因为它可能会在以后回来咬我的屁股。那么我如何在一开始就避免这个问题呢?

您应该将credential=str[i]改为credential==str[i]。你需要双引号=否则它会尝试将credentials设置为str[i]

还好,我找到了一个工作…

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

相关内容

  • 没有找到相关文章

最新更新