if-block未输入,不确定原因

时间:2013-06-17 01:11:08

标签: c++ file fstream

此函数应该读取文件的每一行并将其与用户输入字符串进行比较,并检查它们是否匹配。它基本上可以防止文件中的重复信息。无论如何,该程序没有进入我的“if(loginsFile.is_open())”语句,我不明白为什么。

fstream loginsFile;
loginsFile.open("C:/logins.txt", ios::in | ios::out | ios::trunc | ios :: app | ios:: ate);

string username;
string password;
string info;
bool exists = true;
CheckingAccount cA;
SavingsAccount sA;

do {
    cout << "Enter Username: ";
    cin >> username;
    cout << "Enter Password: ";
    cin >> password;
    cout << endl;
    info = username + " " + password;
    if (loginsFile.is_open()){
        while (loginsFile.good()){
            string line;
            getline(loginsFile, line);
            cout << "line is " << line.substr(line.find_last_of(" ")) << "\n" << "info is " << line.substr(line.find_last_of(" "));
            if (line.substr(line.find_last_of(" ")) == info.substr(0, info.find_last_of(" "))){
                exists = false;
                cout << "Username already exists!" << endl << "Program is not case sensitive!";
            } //end if
        } //end while
    } //end if
} while (exists == true); //end do while

loginsFile << info << endl;
loginsFile.close();
logins[info] = make_pair(cA, sA);
cout << info.substr(0, info.find(' ')) << " Has Been Successfully Registered!" << "\n" << "\n";
return logins;

3 个答案:

答案 0 :(得分:2)

由于文件未打开,因此未输入您的if语句。该文件未打开,因为您无法组合“std :: ios :: trunc”(截断文件删除所有内容)和“std :: ios :: app”(附加到文件末尾),因为它们相互矛盾。< / p>

答案 1 :(得分:0)

调用open()后检查failbit。如果已设置,则打开操作失败。您的道路中的正斜线是否可能导致问题?

答案 2 :(得分:0)

点击此链接:http://www.cplusplus.com/reference/fstream/fstream/open/ 在部分模式中,它说: 如果模式同时设置了trunc和app,则打开操作将失败。如果设置了任何一个但是没有设置,或者设置了app和in,它也会失败。