output within compiler and from exe file differs - c++

i am using turbo c++. when i run the following code from compiler i get different answer at marked point in function result(int) then what i get from running .exe file created.
#include<fstream.h>
#include<conio.h>
#include<process.h>
#include<iomanip.h>
#include<string.h>
#include<stdio.h>
#include<dos.h>
ifstream fil;
int pos[50];
char date[11];
void exitt(int times = 0)
{
cout << endl << endl << " Enter 0 to exit." << endl;
if (times == 0)
cout << " Enter L to return to last screen." << endl;
}
void options();
void companychoose();
void companyscreen(int);
void write(int ch, int pos = 0) //add a check for duplicacy
{
ofstream fout;
clrscr();
if (ch == 1)
{
fout.open("database.dat", ios::binary | ios::app | ios::ate);
char companyname[20], temp;
exitt();
cout << " Enter Company name: ";
gets(companyname);
if (strcmp(companyname, "0") == 0)
exit(0);
else if (strcmp(companyname, "l") == 0)
options();
for (int i = 19; i>0; i--)
companyname[i] = companyname[i - 1];
companyname[0] = '%';
fout << endl;
fout << companyname;
fout.close();
cout << " Add data now?(y/n)" << endl;
askagain:
cin >> temp;
switch (temp)
{
case 'y':
fil.close();
write(2);
break;
case 'n':
options();
break;
default:
cout << " Invalid input" << endl;
goto askagain;
break;
}
}
}
void result(int ch)
{
int high[4], low[4], end, i = 0, enough = 0, temp = 0;
char check[20];
fil.open("database.dat", ios::binary);
fil.seekg(pos[ch], ios::beg);
fil >> check;
cout << endl;
if (check[0] == '%')
{
cout << " Not Enough Data!!!" << endl;
fil.close();
return;
}
while (!fil.eof())
{
if (i == 3)
{
i = 0;
enough = 1;
}
fil >> high[i] >> low[i] >> end >> check;
if (check[0] == '%')
break;
i++;
}
low[i] = 0;
temp = low[0];
if (enough == 0)
cout << " Not Enough Data!!!" << endl;
else
{
for (i = 0; i<3; i++)
{
if (low[i]<low[i + 1])
temp = low[i + 1];
}
if (temp>end)
cout << " Stock Running Low!!";
else if (temp = end)
cout << " Stock Is Stable";
else
cout << " Stock is HIGH!!";
cout << " " << end - temp << endl << endl << endl;
}
fil.close();
}
int read(int ch, int find = 0)
{
clrscr();
result(ch);
fil.open("database.dat", ios::binary);
fil.seekg(pos[ch], ios::beg);
char entry[20];
fil >> entry;
cout << setw(20) << "Date" << setw(10) << "High" << setw(10) << "Low" << setw(10) << "Close" << endl;
while (entry[0] != '%')
{
if (find == 1)
{
if (strcmp(entry, date))
return(fil.tellg() - 11);
else
continue;
}
cout << setw(20) << entry;
fil >> entry;
cout << setw(10) << entry;
fil >> entry;
cout << setw(10) << entry;
fil >> entry;
cout << setw(10) << entry << endl;
fil >> entry;
delay(500);
}
fil.close();
getch();
clrscr();
companyscreen(ch);
}
void edit(int ch)
{
cout << "Enter date of data to be edited";
gets(date);
write(2, read(ch, 1));
}
void companyscreen(int ch)
{
int ch1;
askagain:
result(ch);
cout << " 1. Add Data" << endl;
cout << " 2. Show history" << endl;
cout << " 3. Edit Data" << endl;
exitt();
ch1 = getch() - 48;
if (ch1 == 1)
write(2);
else if (ch1 == 2)
read(ch);
else if (ch1 == 3)
{
read(ch);
edit(ch);
}
else if (ch1 == 0)
{
cout << " exiting!!" << endl;
exit(500);
}
else if (ch1 == 60)
companychoose();
else
{
cout << " Invalid option chosen" << endl;
getch();
clrscr();
goto askagain;
}
}
void companychoose()
{
char name[20];
int i, ch;
clrscr();
fil.open("database.dat", ios::binary);
askagain:
fil.seekg(0, ios::beg);
cout << " Choose Company:";
cout << endl;
i = 1;
while (!fil.eof())
{
fil >> name;
if (name[0] == '%')
{
name[0] = ' ';
pos[i] = fil.tellg();
cout << setw(10) << i << "." << name << endl;
i++;
}
}
fil.close();
exitt();
ch = getch() - 48;
if (ch == 0)
exit(0);
else if (ch == 60)
options();
else if (ch>i)
{
cout << "Invalid choice" << endl;
getch();
clrscr();
goto askagain;
}
clrscr();
companyscreen(ch);
}
void options()
{
int ch;
clrscr();
askagain:
cout << endl << endl;
cout << " 1. Add company" << endl;
cout << " 2. Choose company" << endl;
exitt(1);
ch = getch() - 48;
if (ch == 1)
write(1);
else if (ch == 2)
companychoose();
else if (ch == 0)
{
cout << setw(10) << " Exiting!!";
exit(500);
}
else
{
cout << setw(10) << " Invalid choice chosen" << endl;
getch();
clrscr();
goto askagain;
}
}
void main()
{
clrscr();
textbackground(MAGENTA);
textcolor(WHITE);
clrscr();
options();
getch();
}
pls note that program is yet not fully complete so some features dont work.
i don't know how to include dat file data nor screenshot here.
i don't use visual c++ cause my pc is slow.
i don't use codeblocks cause i dont know how to use it. above code give hundreds of error even after adding "using namespace std;"
pls help me solve it. if you need anything else then ask me. thanks

I get different answer (…) in function result(int) then what I get from running .exe file created.
When you execute your program from the IDE a different working directory is used so different files are seemingly present/missing. Usually the working directory is configurable.
By the way, the goto is not needed. Really, it is not.

Related

Why can't I delete list object in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I tried my best to figure this out but it was unsuccessful :C
PROBLEM
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
FULL CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <list>
#include <ctime>
using namespace std;
struct Treniruote
{
string data, laikas, vardas, pavarde, pratimai;
};
void NuskaitytiIsFailo(list<Treniruote>& treniruotes)
{
string line, word;
fstream file("planas.csv", ios::in);
if (file.is_open())
{
while (getline(file, line))
{
stringstream str(line);
Treniruote row;
if (getline(str, word, ','))
row.data = word;
if (getline(str, word, ','))
row.laikas = word;
if (getline(str, word, ','))
row.vardas = word;
if (getline(str, word, ','))
row.pavarde = word;
if (getline(str, word, ','))
row.pratimai = word;
treniruotes.push_back(row);
}
}
else
cout << "Could not open the file";
}
void rastiKlientoInfo(list<Treniruote>& treniruotes)
{
int a;
string fname, pavarde;
cout << "Write clients surname:";
cin >> pavarde;
cout << "Output to the screen press -1\n";
cout << "Output to the file press - 2\n";
cout << "Output all exercise needed to be done in a week - 3\n";
cout << "Your choice:";
cin >> a;
if (a == 2)
{
cout << "Enter the file name: ";
cin >> fname;
}
else if (a == 3)
{
cout << "Enter the file name: ";
cin >> fname;
}
else
{
}
for (Treniruote& t : treniruotes)
{
if (t.pavarde == pavarde)
{
if (a == 1)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
else if (a == 3)
{
fstream file(fname + ".csv", ios::app);
file << t.pratimai << endl;
}
else
{
fstream file(fname + ".csv", ios::app);
file << t.data << endl;
file << t.laikas << endl;
file << t.vardas << endl;
file << t.pavarde << endl;
file << t.pratimai << endl;
file << endl;
}
}
}
}
void PakeistiReiksmes(list<Treniruote>& treniruotes)
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti duomenys" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >>duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >>duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
t.vardas = t.pavarde = t.pratimai = "obolys";
}
}
}
}
void SukurtiTuscius(list<Treniruote> &treniruotes)
{
for (int i = 27; i <= 30; ++i)
{
stringstream diena;
diena << "2022.11." << i;
for (int j = 8; j <= 19; ++j)
{
stringstream valanda;
valanda << j << ":00-"<< j+1 <<":00";
Treniruote t;
t.data = diena.str();
t.laikas = valanda.str();
t.vardas = t.pavarde = t.pratimai = "nera";
treniruotes.push_back(t);
}
}
}
void ParodytiVisaTvarkarasti(list<Treniruote>& treniruotes)
{
for (Treniruote& t : treniruotes)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
void salinti_pridėti(list<Treniruote>& treniruotes)
{
}
void ProgramosPabaiga(list<Treniruote>& treniruotes)
{
fstream file("planas.csv", ios::out);
for (Treniruote& t : treniruotes)
{
file << t.data <<","<< t.laikas << "," << t.vardas << "," << t.pavarde << "," << t.pratimai;
file << endl;
}
cout << "PROGRAMA BAIGTA";
exit(0);
}
int main()
{
int choice;
bool gameOn = true;
list<Treniruote> treniruotes;
struct tm newtime;
time_t now = time(0);
localtime_s(&newtime,&now);
auto month = to_string(1 + newtime.tm_mon);
auto day = to_string(newtime.tm_mday);
auto hour = to_string(newtime.tm_hour);
auto hour_pridėta = to_string(1 + newtime.tm_hour);
//sukuria .csv faila pagal irasyta pavadinima
//string fname;
//cout << "Enter the file name: ";
//cin >> fname;
// fstream file(fname + ".csv", ios::app);
//Menu
while (gameOn != false) {
cout << "*******************************\n";
cout << " 1 - Create empty weekly plan.\n";
cout << " 2 - Show the full schedule.\n";
cout << " 3 - Read the weekly work plan.\n";
cout << " 4 - Change the schedule field information.\n";
cout << " 5 - Find the given client's full weekly workouts\n";
cout << " 7 - Exit.\n";
cout << "*******************************\n";
for (Treniruote& t : treniruotes)
{
if (t.data == "2022." + month + "." + day)
{
if (t.laikas == hour + ":00-" + hour_pridėta + ":00")
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
}
cout << "*******************************\n";
cout << " Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
SukurtiTuscius(treniruotes);
break;
case 2:
ParodytiVisaTvarkarasti(treniruotes);
break;
case 3:
NuskaitytiIsFailo(treniruotes);
break;
case 4:
PakeistiReiksmes(treniruotes);
break;
case 5:
rastiKlientoInfo(treniruotes);
break;
case 6:
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti langeli" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >> duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >> duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
}
break;
case 7:
{
ofstream file;
file.open("planas.csv", std::ofstream::out | std::ofstream::trunc);
file.close();
ProgramosPabaiga(treniruotes);
break;
}
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
return 0;
}
You must not remove items from a list while iterating through a range-based for loop. Under the hood, the loop stores a begin and end iterator of the original list, and iterate all items between them, and attempting to remove items during the loop will make end unreachable.
Instead, you could simply use std::list::remove_if to remove all elements that satisfy a certain condition:
my_list.remove_if([a, b](const auto& element){
return element.a == a && element.b == b;
};

How to read and store a string value in c++ [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Why must type getline(cin, string) twice?
(5 answers)
Closed 9 months ago.
what's wrong
if I use the get line function only once in the character modifier function the compiler will ignore it
unless I call the function twice
why cant I use it only once?
I tried using other ways, it worked but I wanna understand this one
I'm now just writing random things so the add more details error messages go away
#include <iostream>
#include<string>
using namespace std;
class egybest
{
string link,m;
char sys, type, restart;
int s = 1, e = 1, date;
public:
string charmodifier()
{
//here
getline(cin, m);
getline(cin, m);
for (int x = 0; x <= m.size(); x++)
{
if (m[x] == ' ')
m[x] = '-';
}
return m;
}
~egybest()
{
system("cls");
cout << "do you want to restart the program? y:n;" << endl;
cin >> restart;
system("cls");
if (restart == 'y' || restart == 'Y')
egybest();
else if (restart == 'n' || restart == 'N')
{
system("exit");
}
}
egybest()
{
cout << "do you want to watch a movie or a series? 1:2;" << endl;
cin >> type;
system("cls");
if (type == '1')
linkmovie();
else if (type == '2')
series();
else
cout << "wrong input!" << endl;
}
void linkmovie()
{
cout << "enter the name of the movie:" << endl;
charmodifier();
cout << "enter the release date: " << endl;
cin >> date;
link = "start https://cape.egybest.cool/movie/" + m + "-" + to_string(date);
cout << endl;
system(link.c_str());
}
void series()
{
cout << "do you want it to open links for a particular season, particular episode or all seasons? s:e:a;"
<< endl;
cin >> sys;
system("cls");
if (sys == 'S' || sys == 's')
linkseason();
else if (sys == 'A' || sys == 'a')
linkall();
else if (sys == 'E' || sys == 'e')
linkepisode();
else
cout << "wrong input!" << endl;
}
void linkall()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int j = 1; j <= s; j++)
{
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(j) + "-ep-" + to_string(i);
system(link.c_str());
}
}
cout << endl;
}
void linkepisode()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(e);
cout << endl;
system(link.c_str());
}
void linkseason()
{
cout << "season No." << endl;
cin >> s;
cout << "episodes No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(i);
cout << endl;
system(link.c_str());
}
}
};
int main()
{
egybest egy;
return 0;
}```
The problem is that after entering an integer or a character as for example
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
//...
the input buffer contains the new line character '\n' that corresponds to the pressed Enter key.
So the following call of getline reads an empty string until the new line character is encountered.
In such a case before calling getline you need to remove the new line character from the input buffer like for example
#include <limits>
//...
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
charmodifier();
//...

C++ Hangman Code won't work correctly

my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int instructions();
void manual();
void file(char*);
int letterFill(char, char*, char*);
void Unknown(char*, char*);
const int MAX_LENGTH = 10;
void main()
{
bool done = false;
char word[MAX_LENGTH];
char unknown[MAX_LENGTH];
char letter;
char name[MAX_LENGTH];
int wrong_guesses = 0;
int MAX_TRIES;
char ans;
while (!done)
{
switch (instructions())
{
case 1:
{
manual();
break;
}
case 2:
{
file(word);
break;
}
}
cout << "WHAT IS THE NUMBER OF GUESSES ALLOWED?: " << endl;
cin >> MAX_TRIES;
Unknown(word, unknown);
cout << endl << endl << "HANGMAN";
cout << endl << endl << "Each letter is represented by a star." << endl;
cout << "You have " << MAX_TRIES << " tries left.";
cout << "ENTER GUESS WHEN READY: ";
cin >> letter;
while (letter != 'N' && letter != 'n')
{
while (wrong_guesses < MAX_TRIES)
{
cout << unknown << endl;
cout << "Guess a letter: " << flush;
cin >> letter;
if (letterFill(letter, word, unknown) == 0)
{
cout << endl << "You got it wrong! You lose a guess" << endl;
wrong_guesses++;
}
else
{
cout << endl << "Pfft, you got lucky" << endl;
}
cout << "Guesses Left: " << MAX_TRIES - wrong_guesses << endl;
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You got it!" << endl;
exit(0);
}
cout << "You've been hanged." << endl;
cout << "The word was : " << word << endl;
}
}
cout << "Try again? (y/n): " << flush;
cin >> ans;
if (ans == 'y' || ans == 'Y')
done = true;
else
done = false;
}
system("pause");
}
int instructions()
{
int select = 0;
cout << endl << "HANGMAN" << endl << endl;
cout << " PROGRAM MENU" << endl;
cout << " Select option 1 or 2" << endl << endl;
cout << " 1. INPUT WORD MANUALLY" << endl;
cout << " 2. PLAY AGAINST THE COMPUTER" << endl;
cout << " 3. EXIT PROGRAM BY INPUTING: N or n" << endl << endl;
cin >> select;
return select;
}
void manual()
{
string word;
cout << endl << "INPUT WORD: " << endl;
cin >> word;
return;
}
void file(char *roc)
{
ifstream fin("word.txt");
int x;
int count = 1;
int word;
int i = 0;
srand(time(0));
word = rand() % 20;
while (count < word)
{
fin >> x;
if (x == 0)
{
count++;
}
}
do
{
fin >> x;
roc[i++] = char(x);
} while (x);
return;
}
int letterFill(char guess, char *secretword, char *guessword)
{
int i;
int matches = 0;
for (i = 0; i<MAX_LENGTH; i++)
{
if (secretword[i] == 0)
{
break;
}
if (guess == guessword[i])
{
return 0;
}
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void Unknown(char *word, char *unknown)
{
int i;
int length = strlen(word);
for (i = 0; i<length; i++)
{
unknown[i] = '*';
}
unknown[i] = 0;
}
Again
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.

Saving c++ array of struct to file and issue for adding new elements to it

There are two main problems with my program that I am currently having. The first is I am unable to add more than one account to my program while it is running (I need to close it and re-open before I can add another). The second issue is when I don't add any accounts to my program addresses get saved to the program, this is what the file looks like when I don't add any accounts to the program.
123#John Smith#0#0###-1.07374e+008#-1.07374e+008#
The first part of the file is correct, but the addresses are coming from somewhere else in memory. This is what my code looks like.
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>
#include <sstream>
using namespace std;
struct account
{
string acctNum;
string name;
float cBal;
float sBal;
};
int menu();
char subMenu();
int loadCustomers(account[]);
void saveCusomers(account[], int);
int newCustomer(account[], int);
int deleteCustomer(account[], int);
int findCustomer(account[], int);
void deposit(account[], int);
void withdrawl(account[], int);
void balance(account[], int);
void bankBalance(account[], int);
int main()
{
account acc[20];
int selection;
int numAcc = 0;
int search;
numAcc = loadCustomers(acc);
do
{
selection = menu();
if(selection == 1)
{
newCustomer(acc, numAcc);
}
else if(selection == 2)
{
deleteCustomer(acc, numAcc);
}
else if(selection == 3)
{
search = findCustomer(acc, numAcc);
if (search == -1)
{
cout << "That account doesn't exist." << endl;
system("pause");
system("cls");
}
else
{
cout << right << setw(3) << acc[search].acctNum << "" << left << setw(15) << acc[search].name << acc[search].cBal << acc[search].sBal << endl;
system("pause");
system("cls");
}
}
else if(selection == 4)
{
deposit(acc, numAcc);
}
else if(selection == 5)
{
withdrawl(acc, numAcc);
}
else if(selection == 6)
{
balance(acc, numAcc);
}
else if(selection == 7)
{
bankBalance(acc, numAcc);
}
else if(selection == 8)
{
break;
}
} while (selection != 8);
saveCusomers(acc, numAcc);
return 0;
}
int menu()
{
int select;
cout << "Main Menu" << endl;
cout << "=============" << endl;
cout << "1. New Account" << endl;
cout << "2. Delete Account" << endl;
cout << "3. Find Customer" << endl;
cout << "4. Deposit" << endl;
cout << "5. Withdrawl" << endl;
cout << "6. Balance" << endl;
cout << "7. Bank Balance" << endl;
cout << "8. Exit" << endl;
cout << "=============" << endl;
cout << "Enter choice: ";
cin >> select;
while (select < 1 || select > 8)
{
cout << "Invalid input, select a number between 1 and 8: ";
cin >> select;
}
system("cls");
return select;
}
char subMenu()
{
char choice;
cout << "Which account? <C>hecking or <S>aving: ";
cin >> choice;
while(choice != 'C' && choice != 'c' && choice != 'S' && choice != 's')
{
cout << "Invalid choice, choose either checking or saving: ";
cin >> choice;
}
return choice;
}
int loadCustomers(account acc[])
{
ifstream inFile;
int numCustomers = 0, i = 0;
string ctemp, stemp;
inFile.open("customer.dat");
if (!inFile)
{
cout << "No customer file found." << endl;
}
else
{
cout << "Customer file found..." << endl << endl;
while (getline(inFile, acc[i].acctNum, '#'))
{
getline(inFile, acc[i].name, '#');
getline(inFile, ctemp, '#');
getline(inFile, stemp, '#');
istringstream(ctemp) >> acc[i].cBal;
istringstream(stemp) >> acc[i].sBal;
i++;
numCustomers++;
}
cout << "Number of customers found in file: " << numCustomers << endl;
}
system("pause");
system("cls");
inFile.close();
return numCustomers;
}
void saveCusomers(account acc[], int numCustomers)
{
ofstream outFile;
outFile.open("customer.dat");
for (int i = 0; i < numCustomers; i++)
{
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}
outFile << acc[numCustomers].acctNum;
outFile << '#';
outFile << acc[numCustomers].name;
outFile << '#';
outFile << acc[numCustomers].cBal;
outFile << '#';
outFile << acc[numCustomers].sBal;
outFile << '#';
cout << numCustomers + 1 << " accounts saved into the file." << endl;
outFile.close();
}
int newCustomer(account acc[], int numCustomers)
{
cout << "New Customer" << endl;
cout << "============" << endl;
cout << "Enter account number: ";
cin >> acc[numCustomers].acctNum;
cout << "Enter name: ";
cin.ignore();
getline(cin, acc[numCustomers].name);
acc[numCustomers].cBal = 0;
acc[numCustomers].sBal = 0;
numCustomers++;
return numCustomers;
}
int deleteCustomer(account[], int)
{
return 0;
}
int findCustomer(account acc[], int numCustomers)
{
string target;
cout << "Enter the account number you are looking for: ";
cin >> target;
for (int i = 0; i < numCustomers; i++)
{
if (acc[i].acctNum == target)
{
return i;
}
}
return -1;
}
How can I change this to make it so I can add more than one account when the program is running, and how can I make it so the program won't save an address to my file when nothing is added? I would also like to know why those addresses are being saved like that.
In main() you loadCustomers() in acc[] and you keep a record of the number of customers in local variable numAcc. At the end of main() you saveCustomers() the numAcc in acc[].
1. Your saving function is wrong:
in your loop for (int i = 0; i < numCustomers; i++) { ...}, you first write each customer from 0 to numAcc-1. This is correct.
But afterwards you write again an additional account, with the offset of numAcc. So you're writng one more account than you have. And the values of this account are not initialized, which explains the weird numbers you see.
You do this even if no account was added. And you know that you are doing it, because you've written cout << numCustomers + 1 << " accounts saved into the file."
Correction: just save the accounts you have, in the loop.
2.Your adding function is correct but you don't use it as you've planned:
When you add a customer with newCustomer() your function increments its local variable so that it knows that there is one more customer. Your function correctly returns this new number.
Unfortunately, in main() you do nothing with this returned value, so that numAcc remains unchanged.
Correction: Correct the following statement in main():
if (selection == 1)
{
numAcc = newCustomer(acc, numAcc); // update the number of accounts
}
3. Miscellaneous remarks:
You don't check in newCustomers() if your acc[] array is already full. If you add a 21st account, it'll be a segfault !
The same applies to load. You cannot be sure that nobody added a line to the file with a text editor. So there is as well a risk of reading more lines that there is space in your arry.
Nothing happens in deleteCustomer() I suppose you haven't written it yet. Think that this function could change the number of accounts, exactly as newCustomer().
As most banks have more than twenty customers, I assume that it's an exercise for school. I don't know if you're allowed to do so, but I'd highly recommend to replace arrays with vectors.

reading bytes using fstream c++

I created a read / write of bytes into a binary file using fstream object
#include <iostream>
#include <fstream>
using namespace std;
#define COL_WIDTH 20
int writeBinaryFile(char *desPath);
int readBinaryFile(char *desPath);
int age;
char name[COL_WIDTH];
int recsize = sizeof(int)+sizeof(name);
int n;
int main(){
char desPath[MAX_PATH+1];
char input[2];
while(true){
cout << "Main Menu:\n1 Write Binary File\n2 Read Binary File\n3 EXIT" << endl;
cin.getline(input, 2);
if(atoi(input)== 1){
cout << "Enter destination path:" << endl;
cin.getline(desPath, MAX_PATH+1);
for(;;){
int output = writeBinaryFile(desPath);
if(output == 1) break;
else if(output == 2) { *input = '4'; break;}
}
}
else if(atoi(input) == 2){
cout << "Enter destination path:" << endl;
cin.getline(desPath, MAX_PATH+1);
for(;;){
int output = readBinaryFile(desPath);
if(output == 1) break;
else if(output == 2){ *input = '4'; break;}
}
}
else if(atoi(input) == 3)
break;
else cout << "You entered wrong input, enter only 1 or 2." << endl;
if(atoi(input) == 4) continue;
else break;
}
system("pause");
return 0;
}
int writeBinaryFile(char *desPath){
char option[2];
fstream wBin(desPath, ios::binary | ios::out);
if(!wBin){
cout << desPath << " is not good path."<< endl;
return 1;
}
cout << "Enter name: " << endl;
cin.getline(name,COL_WIDTH);
cout << "Enter age: " << endl;
cin >> age;
cout << "Enter record number: " << endl;
cin >> n;
wBin.seekp(n*recsize);
wBin.write(name, sizeof(name));
wBin.write((char*)&age, sizeof(age));
wBin.close();
cout << "Enter record again? Press:" << endl
<< "Enter to continue" << endl
<< "Q to quit" << endl
<< "M to go back to main menu" << endl;
cin.ignore(256,'\n');
cin.getline(option,2);
if(option[0] == 'q' ||option[0] == 'Q') return 1;
else if(option[0] == 'm' ||option[0] == 'M') return 2;
return 0;
}
int readBinaryFile(char *desPath){
char option[2];
fstream rBin(desPath, ios:: binary | ios:: in);
if(! rBin){
cout << "File not found!" << endl;
return 1;
}
cout << "What record number?" <<endl;
cin >> n;
rBin.seekp((n*recsize));
rBin.read(name,sizeof(name));
rBin.read((char*)&age, sizeof(int));
cout << name <<endl;
cout << age << endl;
rBin.close();
cout << "Print more? Press enter. Press Q to QUIT or M to go back." << endl;
cin.clear();
cin.sync();
cin.getline(option, 2);
if(option[0] == 'q'|| option[0] == 'Q'){rBin.close(); return 1;}
else if(option[0] == 'm' || option[0] == 'M'){rBin.close(); return 2;}
return 0;
}
i created a binary file first with name, age, recordnumber ( position of bytes which is 0) then on second loop i input name, age, recordnumber 2.
When i tried to read the first pair(char*, int) of bytes pos(0) but it returns wrong result but when i tried to read the last pair in pos(1) it returns correct result.
I also tried making 3 times the input, but only the last char* and int is correct.
Why is it getting wrong results in first bytes(name(20bytes),age(4bytes)) but getting correct it last bytes?
In each call to writeBinaryFile the output is reopened, destroying the previous contents of the file.
You'll want to use ios::binary | ios::ate | ios::out | ios::in.
But, this bitmask will not create the file if it does not exist. You can work around that problem with this code sequence:
int writeBinaryFile(char *desPath) {
...
// Create the file only if it doesn't exist
fstream(desPath, ios::binary|ios::out|ios::app);
// Now it exists -- open it
fstream wBin(desPath, ios::binary|ios::out|ios::in);
...
}
Credit #JoeFish for the useful part of the answer.