【发布时间】: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 "如果流已经与文件相关联(即,它已经打开),则调用此函数失败。"