我fstream
没用太多,所以我有点迷路了。我创建了一个文本文件,其中包含一个随机单词列表,我希望将其用作程序的用户名和密码列表。
我希望程序检查用户是否存在(该行中的第一个字符串),然后检查其后的第二个单词是否“匹配”。
到目前为止,我有这个:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("userData.txt");
// Check for error
if (inFile.fail()) {
cerr << "error opening file" << endl;
exit(1);
}
string user, pass;
int Count = 0;
// Read file till you reach the end and check for matchs
while (!inFile.eof()) {
inFile >> user >> pass;
if (user == "Banana", "Apple") {
Count++;
}
cout << Count << " users found!" << endl;
}
}
我的文本文件包含:
香蕉苹果/ n 胡萝卜草莓/ n 巧克力蛋糕/ n 奶酪派/ n
我发现我的代码现在不好,但是我真的不知道我在做什么。
参见下文:
while (!inFile.eof()) {
inFile >> user >> pass;
if (user == "Banana", "Apple") {
Count++; // No point in doing so because this only happens once
}
cout << Count << " users found!" << endl;
}
使用while (inFile >> user >> pass){
代替while (!inFile.eof()){
。为什么?
尝试以下方法:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("userData.txt");
// Check for error
if (inFile.fail()) {
cerr << "error opening file" << endl;
exit(1);
}
string user, pass;
int Count = 0;
// Read file till you reach the end and check for matchs
while (inFile >> user >> pass) {
if (user == "Banana" && pass == "Apple") {
cout <<"user found!" << endl;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句