我正在做一些需要密码的事情。
现在我能够创建文件并存储自定义用户输入,但是我似乎找不到任何地方如何存储具有用户创建值的变量,并使其成为下次程序启动时使用。能够读取该文件并了解其价值。
#include "stdafx.h"
#include "string"
#include "iostream"
#include "fstream"
#include "windows.h"
using namespace std;
int main() {
string user;
string pass;
string entry;
std::ifstream f("test.txt");
if (f.fail()) {
std::ofstream outfile("test.txt");
cout << "Please make a username.\n";
cin >> user;
cout << "Please make a password.\n";
cin >> pass;
outfile << user << std::endl;
outfile << pass << std::endl;
outfile.close();
cout << "Please restart.\n";
int x = 3000;
Sleep(x);
}
else {
cout << "please enter username\n";
cin >> entry;
if (entry == user) {
cout << "Welcome";
int x = 3000;
Sleep(x);
}
else if (entry != user) {
cout << "Nope";
int x = 3000;
Sleep(x);
}
}
return 0;
}
答案 0 :(得分:1)
您尚未添加必要的代码来读取保存的用户名和密码。在函数的else
部分中,添加
f >> user;
f >> pass;
作为前两行。
else {
// Read the user name and password from the file.
f >> user;
f >> pass;
cout << "please enter username\n";
cin >> entry;
if (entry == user) {
cout << "Welcome";
int x = 3000;
Sleep(x);
}
else if (entry != user) {
cout << "Nope";
int x = 3000;
Sleep(x);
}
}
答案 1 :(得分:0)
您可以使用string::find
函数在ifstream
之后的文件中搜索字符串。
if (string1.find(string2) != std::string::npos)
{
std::cout << "found\n";
}
else
{
std::cout << "not found\n";
}