【问题标题】:If-block not entered, not sure why如果没有输入块,不知道为什么
【发布时间】:2013-06-17 01:11:07
【问题描述】:

这个函数应该读取文件的每一行并将其与用户输入的字符串进行比较并检查它们是否匹配。它基本上可以防止文件中的重复信息。无论如何,程序没有进入我的“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;

【问题讨论】:

  • 你在用window7吗? Windows 7 不允许从C: 读取/写入,尝试将其放入c:\\temp\\lognis.txt
  • 路径实际上是我桌面上的一个文件夹。我刚把它删掉了,我发布了这个问题。我没有使用 Windows 7。我使用的是 windows xp prof
  • 你用ios::trunc打开文件...这不是删除所有行吗?如果是这样,你怎么能期望从中阅读?如果没有,也许您没有对该文件的写入权限?
  • 好点,托尼。 Chuck,你确定它没有进入 if,而不是没有进入 while……虽然这会导致无限的外循环……但我想这无论如何都会发生?
  • 您是否已经在程序的其他地方打开了该文件? cplusplus.com/reference/fstream/fstream/open "如果流已经与文件相关联(即,它已经打开),则调用此函数失败。"

标签: c++ file fstream


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    调用 open() 后检查故障位。如果已设置,则打开操作失败。您路径中的正斜杠是否会导致问题?

    【讨论】:

    • 没有路径很好。我在程序的其他部分使用相同的路径,它工作正常。问题在于我认为的 if 块
    • 我不知道什么是失败位。那是c ++的东西吗?哈哈,我是一个刚开始学习 c++ 的 java 人,请原谅我,我不知道所有花哨的术语
    • 您还可以检查 fstream 的 fail() 的返回值,它会检查 failbit 和 badbit:cplusplus.com/reference/ios/ios/fail
    • 作为一名 Java 程序员,您可能已经开始期待诸如调用“open”之类的事情,如果它们失败则抛出异常。如果您在 C++ 中工作很多,则需要检查这些期望。 "assert" 将成为你的朋友。
    【解决方案3】:

    查看此链接:http://www.cplusplus.com/reference/fstream/fstream/open/ 在部分模式下,它说: 如果mode同时设置了trunc和app,则打开操作失败。如果其中任何一个设置了但 out 未设置,或者 app 和 in 都设置了,它也会失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 2013-05-30
      • 2019-01-05
      相关资源
      最近更新 更多