Reputation: 13
I am doing something that requires a password.
right now I am able to create files and store custom user input in that but I cant seem to find anywhere how to store a variable with the user created value, and make it so that the next time the program starts it will be able to read that file and understand the value.
#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;
}
Upvotes: 0
Views: 161
Reputation: 9
You can use string::find
function to search your string in a file after ifstream
.
if (string1.find(string2) != std::string::npos)
{
std::cout << "found\n";
}
else
{
std::cout << "not found\n";
}
Upvotes: 0
Reputation: 206567
You haven't added the necessary code to read the saved user name and password. In the else
part of the function, add
f >> user;
f >> pass;
as the first two lines.
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);
}
}
Upvotes: 1