I just got into programming and was doing a fun little exercise in c++ ( a login app using .dat's as a database ) and ran into a problem. Is there any way to create a "string named file" in a specific directory? I've seen that ones can create both a string named file and a file in a specific directory but cant seem to find the answer for this question. Once again sorry if this has already been gone over and thank you.
This is the part I was on about I'll put the full code down below to get some more opinions as well, just do take in mind that I'm a beginner and the code isn't finished.
int DataBase() {
ofstream DBName(( /*Potencially my directory? + */ BaseAccount + ".dat").c_str());
DBName << Pass << endl;
}
My full code will be down here, im fully open to new suggestions, yet, I do already have some parts of the code that I want to keep them as it is, again do remember that I'm a starter and thank you for your attention!
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <ctype.h>
#include <fstream>
#include <string>
using namespace std;
int UserVar;
string Account, Pass, AccountLog;
int main(), login();
int DataBase() {
ofstream DBName(( /*Potencially my directory? + */ BaseAccount + ".dat").c_str());
DBName << Pass << endl;
}
void wait(int seconds){
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
void DataBaseCheck(string AccCheck){
ifstream DBLookForAcc(AccCheck.c_str());
cout<<"Looking for the user in the data base..."<<endl;
wait(2);
system("cls");
string AccData, AccPass, DBPass;
int DBVarTries=3;
if (DBLookForAcc){
cout<<"Account Found!"<<endl;
wait(1);
system("cls");
ifstream AccData;
AccData.open(AccCheck);
AccData>>DBPass;
do{
cout<<"Please enter your password: ";
cin>>AccPass;
if(AccPass==DBPass){
system("cls");
cout<<"You sucessfully logged in!"<<endl;
exit(0);
}
else (AccPass==DBPass);{
DBVarTries=DBVarTries-1;
system("cls");
cout<<"The password is wrong, please try again!"<<endl<<endl<<DBVarTries<<" attempts remaining. ";
wait(2);
system("cls");
continue;
}
}
while(DBVarTries!=0);
}
else {
system("cls");
cout<<"Sorry... We couldnt find your account."<<endl;
wait(1);
login();
}
}
int login(){
system("cls");
cout<<"Sign in"<<endl<<endl<<endl<<"User Name: " ;
cin>>AccountLog;
system("cls");
DataBaseCheck((AccountLog + ".dat").c_str());
}
int main(){
do{
system("cls");
cout<<"Sign up"<<endl<<endl<<endl<<"Insert your user: ";
cin>>Account;
if(Account=="1"){
do{
login();
}
while(true);
}
cout<<"Insert your accounts password: ";
cin>>Pass;
if(Pass=="1"){
do{
login();
}
while(true);
}
system("cls");
DataBase();
cout<<"The account was saved to the Data Base. ";
wait(2);
system("cls");
UserVar=UserVar+1;
}
while(UserVar=4);
cout<<"You cant sign any more users up."<<endl<<endl<< "Login protocol" ;
login();
}
Related
I am new to write code in c++ programmıng before I just work on java coding. I try to solve teh txt file as database. But I taken this error I search on internet I cound't find the exact answer ? Please if you know help me. Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void menu() {
puts("1. List the products");
puts("2. Add a new product");
puts("3. Sell the new product");
puts("4. Search by Barcode");
puts("5. Exit");
}
int main(int argc, char *argv[]) {
FILE *fProduct;
char name[20];
int quantity;
int barcode;
double price;
menu();
fProduct = fopen("Product.txt", "a+");
if (fProduct != NULL) {
while (!feof(fProduct))
{
printf("Name :");
scanf("%s" , name);
printf("Quantity :");
scanf("%d", &quantity);
printf("Barcode Number :");
scanf("%d", &barcode);
printf("Price :");
scanf("%lf", &price);
printf("Are there any product ???");
}
}
fclose(fProduct);
}
fclose applied a parameter validation assertion.
The fclose function closes stream. If stream is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. ...
In Debug builds, the invalid parameter macro usually raises a failed assertion and a debugger breakpoint before the dispatch function is called. ...
Move your fclose call to be within the if block that checked for NULL.
Based on your screenshot you have a linker error so you may not be running the correct version of your code. Based on the error message I am guessing that the problem is scanf loading data into the name parameter.
1) do a clean build and make sure you do not get any build or linker errrors.
2) if the error still happens then press retry on the screen and the debugger will show you the line that is causing the problem. Use the stack window to find your code on the stack.
If you want it in C++, it is better to write C++ code instead of C code:
// The headers to include are different
#include <iostream>
#include <fstream>
#include <string>
void menu();
int main() {
using namespace std;
ofstream fProduct;
string name;
int quantity;
int barcode;
double price;
// your menu, but for now we handle only the
// case 2: add a new product.
menu();
// as for now we deal only with the insertion of new
// products
// Let's open a new file using the C++ standard library
fProduct.open("Product.txt", ios::out | ios::app | ios::ate);
// If the write can be opened we continue, otherwise
// we skip the next part of the code
if (fProduct.is_open()) {
string conts = "y";
while (conts == "y") {
cout << "Name: "; cin >> name;
cout << "Quantity: "; cin >> quantity;
cout << "Barcode Number: "; cin >> barcode;
cout << "Price: "; cin >> price;
// Here we write in the file the information the user passed us.
// since we are getting information that should be written as
// sequence of char in the file, we could avoid to use
// int/double variables. Let's write in the file, comma
// separated
fProduct << name << "," << quantity << "," << barcode << "," << price << endl;
// Here we have some way to interrupt the loop
cout << "Add another product? [y/n]";
cin >> conts;
}
// Finally we close the file. (only if it was open...)
fProduct.close();
}
return 0;
}
// Your menu function using the standard streams
void menu() {
using namespace std;
cout << "1. List the products" << endl;
cout << "2. Add a new product" << endl;
cout << "3. Sell the new product" << endl;
cout << "4. Search by Barcode" << endl;
cout << "5. Exit" << endl;
}
and if you want it C it's better to use pure C code:
#include <stdio.h>
#include <string.h>
void menu();
int main() {
FILE *fProduct;
// again, all this variable could be simply char[].
char name[20];
int quantity, barcode;
double price;
// As for now our code handles only the insertion of
// new element, not the other choices of the menu
menu();
// Do not check if it is different than NULL,
// check only if it actually is something...
if (fProduct = fopen("Product.txt", "a")) {
char conts = 'y';
while (conts == 'y') {
printf("Name :"); scanf("%s", name);
printf("Quantity :"); scanf("%d", &quantity);
printf("Barcode Number :"); scanf("%d", &barcode);
printf("Price :"); scanf("%lf", &price);
// Let's write in the file
fprintf(fProduct, "%s,%d,%d,%lf\n", name, quantity, barcode, price);
getchar(); // chomps the last newline
printf("Add another product? [y/n] ");
conts = getchar();
}
// At the end of our loop we need to close the file.
fclose(fProduct);
}
return 0;
}
void menu() {
puts("1. List the products");
puts("2. Add a new product");
puts("3. Sell the new product");
puts("4. Search by Barcode");
puts("5. Exit");
}
I really need your help for my C++ homework, Here is what I should do:
1: The user can create a txtfile then input
2:If the user search for that particular txtfile, the program should show the txtfile's contents
3:The user should be able to edit the contents of the txtfile while running the program
I apologize if this had been answered before but I can't find the answer, Please keep the codes as simple as possible as I am still new to programming. I really need your help. Thank you very much.
BTW, I am using Turbo C++ as compiler
Here is my codes:
#include<iostream.h>
#include<stdio.h>
#include<fstream.h>
#include<conio.h>
int main()
{
clrscr();
char name[20], course[20], age[2], num[15], address[30];
char gender[1], bday[15], fn[30], focc[20], mn[30], mocc[20];
char ans, file[30];
int x;
do{
ofstream myfile;
cout<<"File Name: ";
cin>>file;
myfile.open(file,ios_base::out);
cout<<"Student Information \n\n";
cout<<"Name: ";
myfile<<"Name: "<<gets(name);
cout<<"Gender: ";
myfile<<"\nGender: "<<gets(gender);
cout<<"Age: ";
myfile<<"\nAge: "<<gets(age);
cout<<"Address: ";
myfile<<"\nAddress: "<<gets(address);
cout<<"Birthday: ";
myfile<<"\nBirthday: "<<gets(bday);
cout<<"Course: ";
myfile<<"\nCourse: "<<gets(course);
cout<<"Father's name: ";
myfile<<"\nFather's Name: "<<gets(fn);
cout<<"Occupation: ";
myfile<<"\nOccupation: "<<gets(focc);
cout<<"Mother's Name: ";
myfile<<"\nMother's Name: "<<gets(mn);
cout<<"Occupation: ";
myfile<<"\nOccupation: "<<gets(mocc);
myfile.close();
cout<<"\n\nDo you want to edit? [y/n]";
ans = getche();
//ansy
if(ans=='y')
{
clrscr();
x=1;
}
else if (ans=='n')
{
x=0;
}
else
{
cout<<" Invalid choice";
x=0;
}
}while(x!=0);
getch();
return 0;
}
So I wanted to add a stat() check on a dir. After compiling it started tossing some really strange stuff. Heres what I got:
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <boost/algorithm/string.hpp>
#include <sys/stat.h>
using namespace std;
using namespace boost;
struct stat sb;
int main()
{
cout<<" \n";
cout<<" Account Progam\n"
cout<<" \n";
cout<<" Created by: Illyduss\n";
cout<<" 2015\n";
cout<<" \n";
cout<<" \n";
cout<<" \n";
std::string account;
cout<<"Do you already have an account? \n";
cout<<"Type 'NEW' to create an account or enter your account name.\n";
cout<<"Account Name: ";
cin>> account;
cin.ignore();
string str1(account);
to_upper(account);
if (account == "NEW"){
...Some if checking here and junk...
...And then what was recently added the bugs my cin.get()...
else {
cout<< "Welcome back, '" << account << "'!\n";
struct stat sb;
if (stat("/home/user/Account Program/accounts",&sb) == 0 && S_ISDIR(sb.st_mode)){
cout<<"Please enter your password: ";
}
else {
cout<< "There is no account by that name, please type NEW to create a new account.\n";
}
}
}
cin.get();
}
I added cin.get() to keep the terminal open after it's run so I can see whats going on, but I believe it is conflicting with my dir check because it was running just fine until I added that check in to see if an account was already made before attempting to open the account dir.
Specifically I am getting these errors:
intro.cpp:112:2: error: ‘cin’ does not name a type
cin.get();
^
intro.cpp:113:1: error: expected declaration before ‘}’ token
}
^
user#computer:~/Account Program$ g++ intro.cpp
intro.cpp:112:2: error: ‘cin’ does not name a type
cin.get();
^
intro.cpp:113:1: error: expected declaration before ‘}’ token
}
^
As well it is tossing me an error on the } used to close out int main() like once it gets to the dir check it tosses me out of my int main()? Am I not closing off the stat() correctly?
The answer is:
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <boost/algorithm/string.hpp>
#include <sys/stat.h>
using namespace std;
using namespace boost;
struct stat sb;
int main()
{
cout<<" \n";
cout<<" Account Progam\n"
cout<<" \n";
cout<<" Created by: Illyduss\n";
cout<<" 2015\n";
cout<<" \n";
cout<<" \n";
cout<<" \n";
std::string account;
cout<<"Do you already have an account? \n";
cout<<"Type 'NEW' to create an account or enter your account name.\n";
cout<<"Account Name: ";
cin>> account;
cin.ignore();
string str1(account);
to_upper(account);
if (account == "NEW"){
...Some if checking here and junk...
...And then what was recently added the bugs my cin.get()...
else {
cout<< "Welcome back, '" << account << "'!\n";
struct stat sb;
if (stat(("/home/user/Account Program/accounts/"+account).c_str(),&sb) == 0 && S_ISDIR(sb.st_mode)){
cout<<"Please enter your password: ";
}
else {
cout<< "There is no account by that name, please type NEW to create a new account.\n";
}
}
cin.get();
}
I had an extra } after the last else and needed to add the child dir that was being checked via like so ("/home/user/Account Program/accounts/"+account).c_str().
Hey guys i'm working on this simple bank account program with binary files.
For some odd reason, i can't read from the file. Or to be more on point the program crashes whenever i try to read from the file.
Can someone point me in the right direction? Thank you.
Main.cpp
#include <iostream>
#include<fstream>
#include<cstdlib>
#include "Account_Querry.h"
using namespace std;
int main()
{
Account_Querry Account;
int choice;
cout<<"***Acount Information System***"<<endl;
while(true)
{
cout<<"Select one option below ";
cout<<"\n\t1-->Add record to file";
cout<<"\n\t2-->Show All records in file";
cout<<"\n\t3-->Search Record from file";
cout<<"\n\t4-->Update Record";
cout<<"\n\t5-->Delete Record";
cout<<"\n\t6-->Quit";
cout<<"\nEnter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
Account.write_rec();
break;
case 2:
//Account.search_rec();
break;
case 3:
Account.read_rec();
break;
case 4:
//Account.edit_rec();
break;
case 5:
// Account.delete_rec();
break;
case 6:
exit(0);
break;
default:
cout<<"\nEnter corret choice" << endl;
}
}
system("pause");
return 0;
}
Account_Querry.h
#ifndef ACCOUNT_QUERRY_H
#define ACCOUNT_QUERRY_H
#include <string>
#include <fstream>
class Account_Querry
{
private:
int accountNo;
std::string firstName;
std::string lastName;
double balance;
public:
void setAccountNo(int accountNo);
int getAccountNo();
void setFirstName(std::string firstName);
std::string getFirstName();
void setLastName(std::string lastName);
std::string getLastName();
void setBalance(double balance);
double getBalance();
void read_data();
void show_data();
void write_rec();
void read_rec();
void search_rec();
void edit_rec();
void delete_rec();
};
#endif // ACCOUNT_QUERRY_H
Account_Querry.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <math.h>
#include "Account_Querry.h"
using namespace std;
void Account_Querry::setAccountNo(int accountNo)
{
this->accountNo = accountNo;
}
int Account_Querry::getAccountNo()
{
return accountNo;
}
void Account_Querry::setFirstName(string firstName)
{
this->firstName = firstName;
}
string Account_Querry::getFirstName()
{
return firstName;
}
void Account_Querry::setLastName(string lastName)
{
this->lastName = lastName;
}
string Account_Querry::getLastName()
{
return lastName;
}
void Account_Querry::setBalance(double balance)
{
this->balance = balance;
}
double Account_Querry::getBalance()
{
return balance;
}
void Account_Querry::show_data()
{
cout << "Current Information:" << endl;
cout << "-------------------------------------------------" << endl;
cout << "Name: " << firstName << ' ' << lastName << endl;
cout << "Balance: " << balance << endl;
cout << "ID#: " << accountNo << endl;
cout << "-------------------------------------------------" << endl;
cout << endl;
}
void Account_Querry::read_data()
{
cout<<"\nEnter Account Number: ";
cin>>accountNo;
cin.ignore();
cout<<"Enter First Name: ";
getline(cin,firstName,'\n');
cout<<"Enter Last Name: ";
getline(cin,lastName,'\n');
cout<<"Enter Balance: ";
cin>>balance;
}
void Account_Querry::write_rec()
{
ofstream outfile("record.bank", ofstream::app);
read_data();
outfile.write(reinterpret_cast<char *>(this), sizeof(*this));
outfile.close();
system("cls");
}
void Account_Querry::read_rec()
{
ifstream infile;
infile.open("record.bank", ios::binary);
if(!infile)
{
cout<<"Error in Opening! File Not Found!!"<<endl;
return;
}
cout<<"\n****Data from file****"<<endl;
while(!infile.eof())
{
if(infile.read(reinterpret_cast<char*>(this), sizeof(*this))>0)
{
show_data();
}
}
infile.close();
}
First of all, thanks for posting the whole code.
I just created an empty Visual Studio project in Windows and created the 3 files and copied the code you had posted in your question.
The code seems to execute perfectly fine, although while executing, the Option 2 doesn't show all the records in the file. Option 3 does show all the records in the file. You could update the Options section for that.
Apart from that, I compiled to create 32 bit binaries and 64 bit binaries and both of them seemed to work fine. Option 1 is adding new records and Option 3 is printing all the records. If I try to execute Option 3(show all records) before adding even a single record (delete the bank.record file), it is printing error message as well.
Can you tell how you are compiling the code (VisualStudio/gcc/..) on which OS (Windows/Ubuntu/..)?
Also what inputs are you giving while executing. Are you entering any non-ASCII character names like some Japanese characters?
One suggestion is: Not to dump a class object into a binary file (as done in write_rec). Better create a structure with fixed size variables (not using any string/vector).
For example, instead of string use character array, also instead of vector use static array etc. This will avoid a lot of read back issues.
Hope this helps to resolve your issue.
Problem statement:
C++ program that reads a customer’s checking account information calculates his/her account balance.
menu based application should be
developed to perform the following
functionalities iteratively until the user request to quit the program:
1. Display, 2. Deposit, 3. Withdraw, 4. Quit.
This is what I have so far.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
//Main function
int main()
{
//Identify type variables
int x=0;
float amountinput,famount,sum;
string firstname, lastname,date,filename,input,ID,amount;
fstream file;
//Program loop
while(true)
{
//Main menu loop
do
{
cout<<"Enter the number of the option you would like carried out.\n";
cout<<"1. Summary\n";
cout<<"2. Deposit\n";
cout<<"3. Withdraw\n";
cout<<"4. Quit\n";
cin>>x;
}
while(!x);
//When Quit is input, break
if(x==4)
{
break;
}
//Summary display
if (x==1)
{
cout<<"You have selected option number 1. Summary.\n"<<endl;
cout<<"Enter your Cust_ID: ";
cin>>ID;
file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement
\\Cust_"+ID+".dat", ios::in|ios::out|ios::app);
//IF not found error.
if(!file)
{
cout<<"Sorry your account could not be found\n";
}
//Else display all content.
else
{
cout<<endl<<file.rdbuf()<<"\n";
file.close();
}
}
//Deposit
else if(x==2)
{
cout<<"You have selected option number 2. Deposit.\n";
cout<<"Please enter you account ID: ";
cin>>ID;
file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement
\\Cust_"+ID+".dat", ios::in|ios::out|ios::app);
if(!file)
{
cout<<"Sorry the requested account could not be located.\n";
}
else
{
file>>firstname>>lastname;
cout<<endl<<firstname<<" "<<lastname<<endl;
while(!file.eof())
{
file>>date>>amount;
//
//This is mainly where I am missing the lines of code..
//
float atof(string& amount);
cout<<date<<"\t\t"<<amount<<endl;
}
cin.get();cin.get();
cout<<"How much would you like to deposit today.";
cin>>amountinput;
cout<<endl;
file.close();
}
}
else if(x==3);
else if(x==4);
}
cin.get();cin.get(); //or system("PAUSE");
return 0;
}
A sample text file looks like this.
James Bond
01/01/12 200010
03/30/12 -40000
04/30/12 -40000
05/30/12 -40000
06/30/12 -40000
07/30/12 -40000
I have converted the date and amount into strings and have attempted
to convert it into a float and double, and add them up.
I have thought of separating the amounts but I can't manage to do that either.
I have also tried to make make amount a char type.
Any advice to lead me on the right path would be kindly appreciated.
Although it doesn't attempt to be a complete version of your program, here's a bit of code to read the supplied text file, using the first item (after the name) as an initial balance, and the rest as deposits (if they're positive) or withdrawals (if they're negative), reporting the amount of each transaction, and the balance after it's been applied.
#include <iostream>
#include <string>
#include <algorithm>
struct transaction {
std::string date;
double value;
friend std::istream &operator>>(std::istream &is, transaction &t) {
is >> t.date >> t.value;
return is;
}
operator double() { return value; }
};
int main(){
double value;
transaction t;
std::string name;
std::getline(std::cin, name);
std::cin >> t;
value = t;
while (std::cin >> t) {
std::cout << "Transaction: " << t.value;
value += t;
std::cout << "\tBalance: " << value << "\n";
}
std::cout << value;
}