Accessing Variable values from another file c++ - c++

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;
}

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);
}
}

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";
}

Related

Dealing with file io in c++

I have a program that takes input for names and outputs the last names in a string. The task I have now is to include FileIO in it. Specifically, "get user input for the filename, and then read the names from the file and form the last name string."
When I run the program, the console will show the name string from the text file. But only initially. As you keep entering names, that string disappears. Also, my user input for file name seems to be doing nothing, because I can enter anything and it still show the string of last names from the text file.
Here is what I have so far. Included all of it, just to make sure.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
// function declerations
int Menu();
void getName(vector<string> &names, int &count);
void displayName(vector<string> &names, int count);
string getLastNames(vector<string> &names, int count);
int main()
{
vector<string> names;
int count = 0;
int choice = Menu();
ifstream File;
string line;
cout << "Enter file name: ";
getline(cin,line);
File.open("File.txt");
while(File.good()){
getline(File,line);
cout << line << endl;
}
File.close();
while (choice != 0)
{
// switch statement to call functions based on users input
switch (choice)
{
case 1: {
getName(names, count);
} break;
case 2: { displayName(names, count); } break;
case 3: {
cout << getLastNames(names, count) << endl;
} break;
case 0: {
return 0;
} break;
}
choice = Menu();
}
return 0;
}
// function definition for vector of strings
void getName(vector<string> &names, int &count)
{
string name;
// get input for name
cout << "Enter name: ";
getline(cin, name);
// find position of space in string
int pos = name.find(' ');
// reverse order of name
if(pos != -1) {
string first = name.substr(0, pos);
string last = name.substr(pos+1);
name = last + "," + first;
}
// add name to end of vector
names.push_back(name);
count++;
}
// give user option of what to do
int Menu() {
int choice;
cout << "1. Add a name" << endl;
cout << "2. Display names " << endl;
cout << "3. Show all Last Names" << endl;
cout << "0. Quit" << endl;
cout << "Enter a option: ";
cin >> choice;
// if outside of above choices, print 'choice not on list'
while (choice < 0 || choice > 3)
{
cout << "Choice not on list: ";
cin >> choice;
}
cin.ignore();
return choice;
}
// defining function that gets last names
string getLastNames(vector<string> &names, int count) {
stringstream ss;
for (int i = 0; i<count; i++)
{
int pos = names[i].find(',');
if (pos != -1) {
ss << "\"" << names[i].substr(0, pos) << "\", ";
} else {
ss << "\"" << names[i] << "\", ";
}
}
return ss.str();
}
// display the names
void displayName(vector<string> &names, int count)
{
if (count == 0)
{
cout << "No names to display" << endl;
return;
}
for (int i = 0; i<count; i++)
{
cout << names[i] << endl;
}
}

Getting the input from the file as string and also integer C++

I have a text file. I have a text file consisting of member data. I am developing a program where we can get the member data from the file. After searching in the internet, I have searched a way to read all the data from the file as char array. But I want to change it where upon reading from file I want the data to be string and also integer.
name, icno, email, phone_number, acc_num, password ( read from file AS STRING )
month, year ( read from file AS INTEGER )
Content of Membership.txt
Mathavan|021127100897|MathavanKrishnan27#gmail.com|0167750575|1410065449|Mathavan1234|3|2022
Mathavan|021127100897|MathavanKrishnan27#gmail.com|0167750575|1410065448|Mathavan1234|3|2024
Mathavan|021127100897|MathavanKrishnan27#gmail.com|0167750575|1410065447|Mathavan1234|3|2022
string member_login(){
title();
fstream member;
member.open("Membership.txt",ios::in);
string pass_input, line, acc_num1, password1;
int login_attempt = 0, count = 0 , account = 0;
char dummy, resp, accno_input[25], name[25], icno[25],email [40], phone_number[25],acc_num[25],password[25],month[25], year[25];
account_num:
cout << " Enter your account number : ";
cin >> accno_input;
ifstream file("Membership.txt");
while (!file.eof()){
getline(file, line);
count++;
}
cout << accno_input;
int i = 0;
while(i <= count)
{
member.getline(name,25,'|');
member.getline(icno,25,'|');
member.getline(email,40,'|');
member.getline(phone_number,25, '|');
member.getline(acc_num,25, '|');
member.getline(password,25,'|' );
member.getline(month,25,'|' );
member.getline(year, 25);
cout << name << " ";
cout << icno << " ";
cout << acc_num << " ";
cout << accno_input;
if (acc_num == accno_input){
account = 1;
break;
}
i ++;
}
cout << account;
member.close();
if ( account != 1 ){
cout << endl;
cout << " Your account not found !!!"<< endl;
cout << " Please try again !!" << endl << endl;
cout << " PLEASE ENTER ANY KEY TO CONTINUE >>> ";
cin >> dummy;
goto account_num;
}
password1 = password;
cout << endl;
cout << " Enter your account password : ";
cin >> pass_input;
for (login_attempt = 1 ; login_attempt <= 2 ; login_attempt ++){
if (pass_input == password1){
cout << "Login Successful !!!";
break;
}
cout << endl;
cout << "Login Failed. Attempt " << login_attempt << " of 3" << endl;
cout << "Please re-enter Password: " ;
cin >> pass_input;
if (pass_input == password1){
cout << "Login Successful !!!";
break;
}
}
if ( login_attempt == 3){
cout << endl;
cout << "Login Failed. Attempt 3 of 3";
}
return accno_input;
}
There are so many things completely wrong in your program that I do recomend to you:
Delete and start from scratch.
There is no meaningful fix possible. There is even a goto. And you MUST stop using C-Style arrays with some agic dimension in C++. And C++ has many things to make your live easier. Simply use them.
Please find below a C++ solution.
You can copy and paste it and stay as you are, or, you take 3 hours and google all constructs and try to understand and learn and become a better programmer. Your choise.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include <regex>
#include <iterator>
#include <algorithm>
const std::regex re{ R"(\|)" };
struct Member {
// Memeber data
std::string name{};
std::string icno{};
std::string email{};
std::string phoneNumber{};
std::string accountNumber{};
std::string password{};
int month{};
int year{};
// Extractor operator
friend std::istream& operator >> (std::istream& is, Member& m) {
// Readone complete line
if (std::string line{}; std::getline(is, line)) {
// Split it into parts
std::vector parts(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});
// assign parts to member data
if (parts.size() == 8) {
m.name = parts[0]; m.icno = parts[1]; m.email = parts[2]; m.phoneNumber = parts[3]; m.accountNumber = parts[4]; m.password = parts[5];
m.month = std::stoi(parts[6]); m.year = std::stoi(parts[7]);
}
}
return is;
}
};
// Filename for member data
const std::string fileName{ "r:\\Membership.txt" };
int main() {
// Open the data file and check, if it could be opened
if (std::ifstream fileStream{ fileName }; fileStream) {
// Read complete source file, parse it and get all data
std::vector memberData(std::istream_iterator<Member>(fileStream), {});
// We want the user to give 3 trials to enter valid data
constexpr unsigned int MaxTrials = 3u;
unsigned int numberOfTrials{};
// A valid input will stop the loop immediately
bool validInputgiven{};
// Now, try to get the correct input
while (not validInputgiven and numberOfTrials < MaxTrials) {
// Get an acoount number
std::cout << "\nEnter a account number: ";
std::string account{};
std::cin >> account;
// Check, if the account number is in the member data
if (std::count_if(memberData.begin(), memberData.end(), [&](const Member& m) { return m.accountNumber == account; }) > 0) {
// Account info wasOK. Get the password
std::cout << "\nEnter your password: ";
std::string password{};
std::cin >> password;
if (std::count_if(memberData.begin(), memberData.end(), [&](const Member& m) { return m.accountNumber == account and m.password == password; }) > 0) {
// Valid data found
validInputgiven = true;
std::cout << "\n\nEverything OK. Data validated.\n\n";
}
}
// Next try
++numberOfTrials;
if (not validInputgiven and numberOfTrials < MaxTrials) std::cout << "\nInvalid input. Please try again\n\n\n";
}
if (not validInputgiven ) std::cout << "\nToo many wrong tries. Aborting . . .\n\n\n";
}
else std::cerr << "\n\nError. Could not open source file '" << fileName << "'\n\n";
}

Getting an Xstring error in VS in a C++ login program

I am a beginner C++ programmer. I'm trying to create a program that takes logs a user into a program, Everything compiled perfectly, but when I try to run it I get an Xstring error saying this was 0x7FF6F0AACFF0".
I suppose the error could have come from the fact that I am very new to using files in code, and I needed to use them in this program as they were the only way the login and password data could be permanently saved.
I have rewritten this project over 5 times and this is the most functional variant so far. I tried using the ofstream and ifstream but I abandoned them because only one password & login was saved per file; so I think that the main error is probably contained in the Processing and Array_filler functions, all I need is a point in the right direction and I'll probably be able to resolve it.
C++:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
//bug_1 need to fix the error where the code doesn't recognize a returning user
//Project_1 need to implement a subsystem that recommends a random password & Login
//Project_2 need to implement a subsystem that requires a strong password
string Word_blip[90] = {};
string Pass_blop[90] = {};
string password;
string logWord;
string Login_1;
string Pass_1;
int KILL_SWITCH = 1;
int y = 0;
void Array_filler();
void Start_up();
void Yupper_pupper();
void processing();
void New_Login();
int main() {
Start_up();
if (KILL_SWITCH == 0) {
return EXIT_SUCCESS;
}
Yupper_pupper();
processing();
}
void Start_up() {
Array_filler();
cout << "Login:";
cin >> logWord;
cout << "Password:";
cin >> password;
for (y; y >= 90; y++) {
cout << "Preparing" << endl;
}
system("cls");
if (Word_blip[y] == logWord) {
cout << "Login accepted, welcome user:" << endl;
} else if (Word_blip[y] != logWord) {
New_Login();
}
}
void New_Login() {
string i_1_5;
cout << "Login not recognized, would you like to sign up?" << endl;
cin >> i_1_5;
if (i_1_5 == "yes") {
void Yupper_pupper();
} else if (i_1_5 == "no") {
cout << "Have a good day!" << endl;
KILL_SWITCH = 0;
} else {
cout << "That's not a valid answer ;-) please retry" << endl;
New_Login();
}
}
void Yupper_pupper() {
system("cls");
cout << "Please Sign in with your new username & Password." << endl;
cout << "New Login:";
cin >> Login_1;
cout << "New password:";
cin >> Pass_1;
void processing();
}
void processing() {
/* acts like "ofstream" or "ifstream combined; with the
ios::in and ios::out replacing the sort of "read out file"
ofstream meant with "ios::in"and the "input into file" that
ifstream provided with ios::out*/
fstream Urfile("Logins.txt", ios:: in );
string Placeholder_1;
if (Urfile.is_open()) {
getline(Urfile, Placeholder_1);
/* While Urfile = "While the file is open" Urfile = true
When the file runs out of information the file will close
making the statement false and ending the loop ;-)*/
while (Urfile) {
Placeholder_1 = Word_blip[0];
}
Urfile.close();
} else {
cout << "ERROR_OPENING_URFILE_ABORTING_PROGRAM_1" << endl;
abort();
}
fstream Myfile("Passwords.txt", ios:: in );
string Placeholder_2;
if (Myfile.is_open()) {
getline(Myfile, Placeholder_2);
while (Myfile) {
Placeholder_2 = Pass_blop[0];
}
Myfile.close();
} else {
cout << "ERROR_OPENING_MYFILE_ABORTING_PROGRAM_1" << endl;
abort();
}
Start_up();
}
void Array_filler() {
/*This function is responsible for clearing out the file
and replacing everything inside with the contents of Pass_blip and Word_blop
. Don't worry! none of the data will be lost because it was all written to the
arrays to be processed alongside the new inputs*/
fstream Urfile("Login.txt", ios::out);
if (Urfile.is_open()) {
for (int i = 0; Word_blip[i] != "\n"; i++) {
Urfile << Word_blip[i] << endl;
}
Urfile.close();
} else {
cout << "ERROR_OPENING_URFILE_ABORTING_PROGRAM_2" << endl;
abort();
}
fstream Myfile("Passwords.txt", ios::out);
if (Myfile.is_open()) {
for (int i = 0; Pass_blop[i] != "\n"; i++) {
Myfile << Pass_blop[i] << endl;
}
Myfile.close();
} else {
cout << "ERROR_OPENING_MYFILE_ABORTING_PROGRAM_2" << endl;
abort();
}
}

I'm only able to input one word into the file

Like my title said, I am having problems with file input.
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void CreateNewFile(const string FileName) {
ofstream NewFile;
string FileNamePlaceholder = FileName + ".txt";
NewFile.open(FileNamePlaceholder);
cout << "What would you like to write to the file? ";
string InputForFile;
cin >> InputForFile;
NewFile << InputForFile;
NewFile.close();
cout << "You will now be able to view the file in your computer.\n";
}
void Start() {
char NewFile;
cout << "Would you like to create a new file? [Y/N] ";
cin >> NewFile;
if (NewFile == 'y' || NewFile == 'Y') {
cout << "What would you like the new file to be named? ";
string NewFileName;
cin >> NewFileName;
CreateNewFile(NewFileName);
}
else if (NewFile == 'n' || NewFile == 'N') {
cout << "Ok, bye.\n";
}
else {
cout << "You did not type y, Y, n, or N!\n";
}
}
int main(void) {
Start();
return 0;
}
For some reason, I can only input one word at a time into the file. I'm sorry if this is an obvious answer. Any help would be appreciated.

c++:reading from file/parse string

I am currently working on a program, where the user of the program is required to input username and password, and the program will do the search and see if there is such user, if it exists, then proceeding to a screen with further options, or reenter the username.
The username.txt files that stores the username and password includes the following data:(first column is username, and second is password)
john,abc
marry,cde
admin,admin
joseph,1234
My code is as follows, but it doesnt work, after i input username and password, the programs automatically closes. Can you help me with it? Is there something wrong with my parsing the string into 2?
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<math.h>
#include<stdio.h>
using namespace std;
void printoptionsadmin(){
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout\n5.Shutdown" << endl;
}
void printoptions(){
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout" << endl;
}
void main()
{
cout << "Please login." << endl;
stop:
string usertype;//user input
string passtype;//user input
string line;
string manager = "admin";
string managerp = "admin";
string user;//read from file
string pass;//read from file
ifstream openfile("username.txt");
cout << "Enter your username:";
cin >> usertype;
cout << "Enter your password:";
cin >> passtype;
bool found = false;
while (found&&getline(openfile, line))
{
stringstream iss(line);
getline(iss, user, ',');
getline(iss,pass);
if (usertype == manager && passtype == managerp)//admin login
{
void printoptionsadmin();
found = true;
break;
}
else if (usertype== user && passtype== pass)//regular login
void printoptions();
else
{
cout << "Invalid username or password, please start over." << endl;
goto stop;//going back to login screen
}
openfile.close();
}
}
I altered your code a bit, you messed up the found, plus i removed the goto, also you don't have to explicitly close the file, it is closed when the scope is left(RAAI).
I suggest you to add some checks to your code (file ok? read of line ok? ...)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
static const string PASSWORD_FILE("username.txt");
static const string MANAGER_USER = "admin";
static const char DELIM = ',';
void printoptionsadmin() {
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout\n5.Shutdown"
<< endl;
}
void printoptions() {
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout" << endl;
}
string login() {
ifstream passwordFile(PASSWORD_FILE);
string usertype; //user input
string passtype; //user input
cout << "Enter your username:";
cin >> usertype;
cout << "Enter your password:";
cin >> passtype;
for (string userPasswordLine; getline(passwordFile, userPasswordLine);) {
stringstream ss(userPasswordLine);
string user, password;
getline(ss, user, DELIM);
getline(ss, password, DELIM);
if (user == usertype && password == passtype) {
return user;
} // if
} // for
return "";
}
int main() {
cout << "Please login." << endl;
string loggedInUser;
while ((loggedInUser = login()) == "") {
cerr << "Login failed" << endl;
} // while
if (loggedInUser == MANAGER_USER) {
printoptionsadmin();
} else {
printoptions();
} // else
return 0;
}
Each getline() without third parameter will read a new line and it will provide you something that you are not needed here.
So use " " white space as the delimiter in getline() function instead of default "\n".
Also another thing is your while loop condition is always false since found is initialized to false. So it will not go inside while loop
Here is the logic you needed,
bool found = false;
while (found&&getline(openfile, line))
bool found = false;
std::string delimiter = ",";
while (getline(openfile, line, " "))//To read upto each " "(white space instead of next line(\n is default third parameter)
{
/* Splitting the UserName & Password using ','*/
user = line.substr(0, line.find(delimiter));
pass = line.substr(line.find(delimiter)+1, -1);
if (usertype == manager && passtype == managerp)//admin login
{
void printoptionsadmin();
found = true;
break;
}
else if (usertype== user && passtype== pass)//regular login
void printoptions();
else
{
cout << "Invalid username or password, please start over." << endl;
goto stop;//going back to login screen
}
openfile.close();
}