cross initialization error in while loop (c++ program) - c++

I am doing a lot of things wrong here. Plz help.
#include <iostream>
#include <fstream>
using namespace std;
class student {
int rno;
char name[15];
float marks;
public:
void getdata()
{
cout << "\nEnter Roll No. : ";
cin >> rno;
cout << "\nEnter Name : ";
cin >> name;
cout << "\nEnter Marks : ";
cin >> marks;
};
void writedata()
{
fstream input;
input.open("stu.dat", ios::out | ios::app);
input.write((char*)this, sizeof(student));
input.close();
};
void readdata()
{
int temp;
cout << "\nEnter roll no: ";
cin >> temp;
fstream output;
output.open("stu.dat", ios::in);
output.seekg(0, ios::beg);
while (output.read((char*)this, sizeof(student))) {
if (rno == temp) {
cout << "\nRoll no. : " << rno
<< "\nName : " << name
<< "\nMarks : " << marks;
}
else {
cout << "\nWrong Roll no entered";
};
};
};
};
int main()
{
student s[25];
student* st;
char ans = 'y', ans2 = 'y', ans3 = 'y';
int o, i = 0, j = 0;
do {
cout << "\nEnter your choice\n1.Write\n2.Read";
cin >> o;
switch (o) {
case 1:
while (ans2 == 'y' || ans2 == 'Y') {
s[i].getdata();
s[i].writedata();
cout << "\nDo you want to continue?";
cin >> ans2;
i++;
};
break;
case 2:
while (ans3 == 'y' || ans3 == 'Y') {
st->readdata();
cout << "\nDo you want to continue?";
cin >> ans3;
j++;
};
break;
};
} while (ans == 'y' || ans == 'Y');
return 0;
}

All seems well until line 82:
st->readdata();
where the variable st is not initialised but used.

Related

can't extract data from a structure array c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
the program works fine and executes all options, but in the 3rd and 4th option, in 3rd when i search for a student the program doesn't go beyond the data input part while in 4th when i search for data and print it, it gives garbage values in the variables with int datatype while doesn't display string or char type variables. any help would be much appreciated. EDIT: sorry for the inconvenience, I've now separated the functions form the main code. Hope its its more understandable now.
#include<iostream>
#include<string>
using namespace std;
int ncr;
int me,n=0,u,y,l;
char opt1,opt2,opt3,opt4;
struct student
{
string Name;
int DoB;
int Age;
string Address;
string Course[5];
char grade[5];
};
void add();
void remove();
void update();
void search();
int main()
{ int opt;
student s[n];
while(1)
{
cout<<" select what you want to do \n\n 1. Add new record \n2. Remove record\n3. Update Record\n4. Search for particular student\n" ;
cin>>opt;
if(opt==1)
{add();}
else if(opt==2)
{remove();}
else if(opt==3)
{update();}
else if(opt==4)
{search();}
}
}
.
void add(){
n++;
student s[n];
do
{ cout<<"enter name of student ";
cin>>s[n-1].Name;
cout<<"enter DoB of student ";
cin>>s[n-1].DoB;
cout<<"enter age of student ";
cin>>s[n-1].Age;
cout<<"enter address of student ";
cin>>s[n-1].Address;
cout<<"enter courses and grades (max 5) \n";
for(int x=0;x<5;x++){
cout<<"course:";
cin>>s[n-1].Course[x];
cout<<"grade:";
cin>> s[n-1].grade[x];}
cout<<"Roll No. : "<<n<<"\nName :"<<s[n-1].Name<<"\nDoB :"<<s[n-1].DoB<<"\nAge :"<<s[n-1].Age<<"\nAddress :"<<s[n-1].Address;
for(int x=0;x<5;x++){
cout<<"\n"<<s[n-1].Course[x];
cout<<" grade : "<< s[n-1].grade[x]<<"\n";}
cout<<"repeat for another student 'y' or 'n' ?";
cin>>opt1;
}
while(opt1=='y'|| opt1=='Y');
}
.
void remove(){student s[n];
do
{
cout<<"enter student roll no to remove data";cin>>l;
for(int i=l;i<n;i++)
{ s[l-1].Name=s[l].Name;
s[l-1].DoB= s[l].DoB;
s[l-1].Age=s[l].Age;
s[l-1].Address=s[l].Address;
for(int j=0;j<5;j++){
s[l-1].Course[j]=s[l].Course[j];
s[l-1].grade[j]=s[l].grade[j];}
}
cout<<"Record Removed\n";
n--;
cout<<"repeat ? 'y' or 'n' ";
cin>>opt2;
}
while(opt2 == 'y' || opt2 == 'Y');}
.
void update(){
student s[n];
do
{
cout<<"enter the roll no of student you want to update data";
cin>>u;
cout<<"Roll No. : "<<u;
cout<<"\nName : ";
cout<<s[u-1].Name;
cout<<"\nDoB : ";
cout<<s[u-1].DoB;
cout<<"\nAge : ";
cout<<s[u-1].Age;
cout<<"\nAddress :";
cout<<s[u-1].Address;
cout<<"\nCourses and Grades\n";
for(int r=0;r<5;r++)
{
cout<<s[u-1].Course[r];
cout<<"\t"<< s[u-1].grade[r]<<endl;
}
cout<<"enter name of student ";
cin>>s[u-1].Name;
cout<<"enter DoB of student ";
cin>>s[u-1].DoB;
cout<<"enter age of student ";
cin>>s[u-1].Age;
cout<<"enter address of student ";
cin>>s[u-1].Address;
cout<<"enter courses and grades (max 5) \n";
for(int x=0;x<5;x++){
cout<<"course:";
cin>>s[u-1].Course[x];
cout<<"grade:";
cin>> s[u-1].grade[x];}
cout<<"Roll No. : "<<u;
cout<<"\nName : ";
cout<<s[u-1].Name;
cout<<"\nDoB : ";
cout<<s[u-1].DoB;
cout<<"\nAge : ";
cout<<s[u-1].Age;
cout<<"\nAddress :";
cout<<s[u-1].Address;
cout<<"\nCourses and Grades\n";
for(int r=0;r<5;r++)
{ cout<<s[u-1].Course[r];
cout<<"\t"<< s[u-1].grade[r]<<endl; }
cout<<"repeat ? 'y' or 'n' ";
cin>>opt3;
}
while(opt3 == 'y' || opt3 == 'Y');
}
.
void search(){
student s[n];
do
{
cout<<"enter the roll no of student you want to search data of";
cin>>y;
cout<<"Roll No. : "<<n<<"\nName :"<<s[y-1].Name<<"\nDoB :"<<s[y-1].DoB<<"\nAge :"<<s[y-1].Age<<"\nAddress :"<<s[y-1].Address<<"\nCourses and Grades\n";
for(int r=0;r<5;r++)
{
cout<<s[y-1].Course[r];
cout<<"\t"<< s[y-1].grade[r]<<endl;
}
cout<<"repeat ? 'y' or 'n' ";
cin>>opt4;
}
while(opt4 == 'y' || opt4 == 'Y');}
This should look a bit more like a code intended for humans to read :)
#include<iostream>
#include<string>
using namespace std;
int ncr;
int me,n=0,u,y,l;
char opt1,opt2,opt3,opt4;
struct student
{
string Name;
int DoB;
int Age;
string Address;
string Course[5];
char grade[5];
};
void add();
void remove();
void update();
void search();
int main()
{
int opt;
student s[n];
while(1)
{
cout << " select what you want to do \n\n 1. Add new record \n2. Remove record\n3. Update Record\n4. Search for particular student\n" ;
cin >> opt;
if(opt==1)
{
add();
}
else if(opt==2)
{
remove();
}
else if(opt==3)
{
update();
}
else if(opt==4)
{
search();
}
}
}
void add()
{
n++;
student s[n];
do
{
cout << "enter name of student ";
cin >> s[n-1].Name;
cout << "enter DoB of student ";
cin >> s[n-1].DoB;
cout << "enter age of student ";
cin >> s[n-1].Age;
cout << "enter address of student ";
cin >> s[n-1].Address;
cout << "enter courses and grades (max 5) \n";
for(int x=0;x<5;x++)
{
cout<<"course:";
cin>>s[n-1].Course[x];
cout<<"grade:";
cin>> s[n-1].grade[x];
}
cout << "Roll No. : " << n << "\nName :" << s[n-1].Name << "\nDoB :" << s[n-1].DoB << "\nAge :" << s[n-1].Age << "\nAddress :" << s[n-1].Address;
for( int x = 0; x < 5; x++ )
{
cout << "\n"<<s[n-1].Course[x];
cout << " grade : "<< s[n-1].grade[x]<<"\n";}
cout << "repeat for another student 'y' or 'n' ?";
cin >> opt1;
}
while(opt1=='y'|| opt1=='Y');
}
void remove()
{
student s[n];
do
{
cout << "enter student roll no to remove data";
cin >> l;
for( int i=l; i < n; i++ )
{
s[l-1].Name=s[l].Name;
s[l-1].DoB= s[l].DoB;
s[l-1].Age=s[l].Age;
s[l-1].Address=s[l].Address;
for(int j=0;j<5;j++)
{
s[l-1].Course[j]=s[l].Course[j];
s[l-1].grade[j]=s[l].grade[j];
}
}
cout<<"Record Removed\n";
n--;
cout << "repeat ? 'y' or 'n' ";
cin >> opt2;
}
while(opt2 == 'y' || opt2 == 'Y');
}
void update()
{
student s[n];
do
{
cout << "enter the roll no of student you want to update data";
cin >> u;
cout << "Roll No. : " << u;
cout << "\nName : ";
cout << s[u-1].Name;
cout << "\nDoB : ";
cout << s[u-1].DoB;
cout << "\nAge : ";
cout << s[u-1].Age;
cout << "\nAddress :";
cout << s[u-1].Address;
cout << "\nCourses and Grades\n";
for( int r=0; r < 5; r++ )
{
cout << s[u-1].Course[r];
cout << "\t"<< s[u-1].grade[r] << endl;
}
cout << "enter name of student ";
cin >> s[u-1].Name;
cout << "enter DoB of student ";
cin >> s[u-1].DoB;
cout << "enter age of student ";
cin >> s[u-1].Age;
cout << "enter address of student ";
cin >> s[u-1].Address;
cout << "enter courses and grades (max 5) \n";
for(int x=0; x < 5; x++ )
{
cout<<"course:";
cin>>s[u-1].Course[x];
cout<<"grade:";
cin>> s[u-1].grade[x];
}
cout << "Roll No. : " << u;
cout << "\nName : ";
cout << s[u-1].Name;
cout << "\nDoB : ";
cout << s[u-1].DoB;
cout << "\nAge : ";
cout << s[u-1].Age;
cout << "\nAddress :";
cout << s[u-1].Address;
cout << "\nCourses and Grades\n";
for( int r = 0; r < 5; r++)
{
cout << s[u-1].Course[r];
cout << "\t"<< s[u-1].grade[r]<<endl;
}
cout << "repeat ? 'y' or 'n' ";
cin >> opt3;
}
while(opt3 == 'y' || opt3 == 'Y');
}
void search()
{
student s[n];
do
{
cout << "enter the roll no of student you want to search data of";
cin >> y;
cout << "Roll No. : " << n << "\nName :" << s[y-1].Name << "\nDoB :" << s[y-1].DoB << "\nAge :" << s[y-1].Age << "\nAddress :" << s[y-1].Address << "\nCourses and Grades\n";
for( int r=0; r < 5; r++ )
{
cout << s[y-1].Course[r];
cout << "\t" << s[y-1].grade[r]<<endl;
}
cout << "repeat ? 'y' or 'n' ";
cin >> opt4;
}
while( opt4 == 'y' || opt4 == 'Y' );
}
The problem you're having is with the scope of your programme.
In the main() function you declare an array, which presumably should be holding all the records. However for every option (function add/remove/update/search) you declare a new one. These arrays are local to those functions and are being "forgotten" after the function is finished.
In order to fix that, you have to pass the original array (the one from main()) to those functions.
The next problem, which is more severe is the fact, that you can't change the size of an array in the runtime! The elements you were accessing in the 3rd option were some random bytes in the memory and this can cause a lot of trouble.
Either create an array with e.g. 100 fields ( student s[100]; ), or even better try using std::vector, which can size you can adjust according to the number of records.
Third thing, remember that formatting code is extremely important. Hopefully it was just a copy-paste problem that made your code look unreadable, but if it's not the case then try to change. Well formatted code is easier to understand and will make it easier for you to debug it.

How to read/write doubles in a binary file?

I am creating a program that will write and read the content of a binary file. The part I am struggling with is reading/writing pointsEarned and studentGPA as a double. It prints out 6.36599e-314 instead of the number I provided. I looked around the web for a solution but couldn't find one, so here I am.
class student {
int studentID;
char name[30];
char lastName[30];
double pointsEarned;
double studentGPA;
public:
void getData() {
cout << "\nEnter the Student ID: ";
cin >> studentID;
cout << "\n\nEnter the first name of the student: ";
cin >> name;
cout << "\n\nEnter the last name of the student: ";
cin >> lastName;
cout << "\n\nEnter the amount of points earned by the student: ";
cin >> pointsEarned;
cout << "\n\nEnter the Student GPA: ";
cin >> studentGPA;
}
void showData() {
cout << "\nStudent ID: " << studentID;
cout << "\nStudent Name: " << name << " " << lastName;
cout << "\nPoints: " << pointsEarned;
cout << "\nGPA: " << studentGPA << "\n";
}
int studentNumber() {
return studentID;
}
};
//input student info into the dat file
void write() {
student object;
student val;
ofstream file2;
file2.open("student.dat", ios::binary | ios::app);
object.getData();
file2.write((char *)&object, sizeof(object));
file2.close();
}
void display() {
student object;
ifstream file1;
file1.open("student.dat", ios::binary);
if (!file1) {
cout << "File not Found!\n";
}
else {
//read data
while (file1.read((char *)&object, sizeof(object))) {
object.showData();
}
}
file1.close();
}
//display student information through their studentID
void search(int n) {
student object;
ifstream file1;
file1.open("student.dat", ios::binary);
if (!file1) {
cout << "File not Found!\n";
}
else {
while (file1.read((char *)&object, sizeof(object))) {
if (object.studentNumber() == n)
object.showData();
//validation
if (object.studentNumber() != n) {
cout << "StudentID doesn't exist\n";
break;
}
}
}
file1.close();
}
//delete student
void deleteRecord(int n) {
student object;
//open both files
ifstream file1;
file1.open("student.dat", ios::binary);
ofstream file2;
file2.open("Temp.dat", ios::out|ios::binary);
//write contents of f1 to f2
while (file1.read((char*)&object, sizeof(object))) {
if (object.studentNumber() != n)
file2.write((char*)&object, sizeof(object));
}
file1.close();
file2.close();
//delete original file and rename the new one
remove("student.dat");
rename("Temp.dat", "student.dat");
}
void editRecord(int n) {
fstream fp;
student object;
int found = 0;
fp.open("student.dat", ios::in | ios::out);
while (fp.read((char *)&object, sizeof(object)) && found == 0) {
if (object.studentNumber() == n) {
object.showData();
cout << "\nEnter The New Details of student";
object.getData();
int pos = -1 * sizeof(object);
fp.seekp(pos, ios::cur);
fp.write((char*)&object, sizeof(object));
found = 1;
}
//validation
if (object.studentNumber() != n) {
cout << "StudentID doesn't exist\n";
break;
}
}
fp.close();
}
int main() {
int n;
int studentIDNumber;
cout << " Press 1 if you choose to input student information\n Press 2 to display all student's information\n Press 3 to display a specific student's information\n Press 4 to modify student information\n Press 5 to delete a student\n";
cin >> n;
if (n == 1) {
write();
} else if(n == 2){
display();
}
else if (n == 3) {
cout << "Enter the Student ID to get the student information: ";
cin >> studentIDNumber;
search(studentIDNumber);
}
else if (n == 4) {
cout << "Enter the Student ID to modify the student information: ";
cin >> studentIDNumber;
editRecord(studentIDNumber);
}
else if (n == 5) {
deleteRecord(studentIDNumber);
cout << "The record has been deleted.\n";
}
else {
cout << "Error. The number is neither 1 or 2. Please try again. \n";
}
return 0;
}
The output:
Student ID: 55
Student Name: John Doe
Points: 6.36599e-314
GPA: 7.27464e+199
Press any key to continue . . .

Can't figure out error when adding to an array

I am having a hard time figuring this out. Everything else in my project is working so far, but when I try to add to my array of objects, it crashes. I get an error of cannot read string. This is the message, I have tried so many things. Here is the error, and it crashes after the input on the SetNewAccountInfo() function. I am new to programming, and hope this code is formatted on here right. This is a school project so I'm not asking for the answer, maybe just explain why I am unable to add to my array in laymen terms. Pointers and such are confusing so far.
static _Elem *__CLRCALL_OR_CDECL copy(_Elem *_First1, const _Elem *_First2, size_t _Count)
{ // copy [_First2, _First2 + _Count) to [_First1, ...)
**return (_Count == 0 ? _First1** : (_Elem *)_CSTD memcpy(_First1, _First2, _Count));
}
// TestClassC.cpp : main project file.
#include "stdafx.h"
#include "BankClassType.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <ostream>
using namespace std;
void MainMenu(BankClassType bo[],int num, int cAcct);
void AcctOptionsMenu(BankClassType bo[], int num, int cAcct);
int SetNewAccountInfo();
void PrintAccountInfo();
void AccountDeposit();
void AccountWithdrawal();
int main()
{
const int num = 4;
BankClassType *bo = new BankClassType[num];
BankClassType b;
BankClassType bo0("12345", 'P', "Gates", "Bill", 175253.99, 6875250.23);
BankClassType bo1("12346", 'R', "Jones", "Tommy", 845.21, 2700.00);
BankClassType bo2("12347", 'P', "Asimov", "Isaac", 300.67, 14750.29);
bo[0] = bo0;
bo[1] = bo1;
bo[2] = bo2;
int cAcct = 3;
b.MainMenu(bo, num, cAcct);
_getch();
return 0;
}
//BankClassType.h File
#pragma once
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <ostream>
#ifndef BankClassType_h
#define BankClassType_h
using namespace std;
class BankClassType
{
private:
string AccountNumber;
string FirstName;
string LastName;
double CheckingBalance;
double SavingsBalance;
char AccountType;
public:
BankClassType()
{
FirstName = "";
LastName = "";
AccountNumber = "";
AccountType = 'p';
CheckingBalance = 0;
SavingsBalance = 0;
}
BankClassType(string acctNumber, char acctType, string lname, string fname, double cBal, double sBal);
//~BankClassType();
void SetNewAccountInfo(BankClassType bo[], int num, int cAcct);
void PrintAccountInfo();
void AccountDeposit(BankClassType bo[], int number, int num, int cAcct);
void AccountWithdrawal(BankClassType bo[], int number, int num, int cAcct);
void AcctOptionsMenu(BankClassType bo[], int num, int cAcct);
void MainMenu(BankClassType bo[], int num, int cAcct);
//void ExistingAccounts(string acctNumber, char acctType, string lname, string fname, double cBal, double sBal);
string getAccountNumber()
{
return AccountNumber;
}
char getAccountType()
{
return AccountType;
}
double getCheckingBalance(double amount)
{
CheckingBalance = CheckingBalance + amount;
return CheckingBalance;
}
double getSavingsBalance(double amount)
{
SavingsBalance = SavingsBalance + amount;
return SavingsBalance;
}
double getWithdrawalCheckingBalance(double amount)
{
CheckingBalance = CheckingBalance - amount;
return CheckingBalance;
}
double getWithdrawalSavingsBalance(double amount)
{
SavingsBalance = SavingsBalance - amount;
return SavingsBalance;
}
string getFirstName()
{
return FirstName;
}
string getLastName()
{
return LastName;
}
};
#endif
//BankClassImp.cpp
#include "stdafx.h"
#include "BankClassType.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <ostream>
using namespace std;
BankClassType::BankClassType(string acctNumber, char acctType, string lname, string fname, double cBal, double sBal)
{
AccountNumber = acctNumber;
AccountType = acctType;
LastName = lname;
FirstName = fname;
CheckingBalance = cBal;
SavingsBalance = sBal;
/*cout << "\nName: " << LastName << ", " << FirstName;
cout << "\nAccountNumber: " << AccountType << AccountNumber;
cout << "\nChecking Balance: " << CheckingBalance;
cout << "\nSavings Balance: " << SavingsBalance<<endl;
*/
}
/*BankClassType::~BankClassType()
{
delete[] FirstName;
delete[] LastName;
delete[] AccountNumber;
delete[] AccountType;
}*/
void BankClassType::SetNewAccountInfo(BankClassType bo[], int num, int cAcct)
{
//BankClassType * bt = new BankClassType;
BankClassType c;
string fName;
string acctNum;
string lName;
char accType;
double cBal, sBal;
if (cAcct >= 5)
{
"Sorry the accounts are currently full, press any key to return to main menu: ";
c.MainMenu(bo, num, cAcct);
_getch();
}
else
cout << "\nEnter the 5 digit account number: "; cin >> acctNum;
cout << "\nEnter the account type (p) or (r): "; cin >> accType;
cout << "\nEnter the first name: "; cin >> fName;
cout << "\nEnter the last name: "; cin >> lName;
cout << "\nEnter the checking balance: "; cin >> cBal;
cout << "\nEnter the savings balance: "; cin >> sBal;
BankClassType bo3(acctNum, accType, lName, fName, cBal, sBal);
bo[cAcct + 1] = bo3;
}
void BankClassType::PrintAccountInfo()
{
cout << "Name: " << LastName << ", " << FirstName;
cout << "\nAccountNumber: " << AccountType << AccountNumber;
cout << "\nChecking Balance: " << CheckingBalance;
cout << "\nSavings Balance: " << SavingsBalance << endl << endl;
}
void BankClassType::AccountDeposit(BankClassType bo[], int number, int num, int cAcct)
{
int choice;
BankClassType b;
cout << "\nEnter 1 for checking or 2 for savings: ";
cin >> choice;
if (choice == 1)
{
double amount;
cout << "Enter amount to deposit into checking: " << endl;
cin >> amount;
bo[number].getCheckingBalance(amount);
cout << "You added $" << amount << " to checking account number " << bo[number].getAccountNumber();
_getch();
b.MainMenu(bo, num, cAcct);
}
else if (choice == 2)
{
double amount;
cout << "Enter amount to deposit into savings: " << endl;
cin >> amount;
bo[number].getSavingsBalance(amount);
cout << "You added $" << amount << " to savings number" << bo[number].getAccountNumber();
_getch();
b.MainMenu(bo, num, cAcct);
}
else
{
cout << "Incorrect Input, try again: ";
_getch();
AccountDeposit(bo, number, num, cAcct);
}
}
void BankClassType::AccountWithdrawal(BankClassType bo[], int number, int num, int cAcct)
{
int choice;
BankClassType b;
cout << "\nEnter 1 for checking or 2 for savings: ";
cin >> choice;
if (choice == 1)
{
double amount;
cout << "Enter amount to withdrawal from checking: " << endl;
cin >> amount;
bo[number].getWithdrawalCheckingBalance(amount);
cout << "You withdrew $" << amount << " from checking account number " << bo[number].getAccountNumber();
cout << "\nPress any key to return to main menu: ";
_getch();
b.MainMenu(bo, num, cAcct);
}
else if (choice == 2)
{
double amount;
cout << "Enter amount withdrawal from savings: " << endl;
cin >> amount;
bo[number].getWithdrawalSavingsBalance(amount);
cout << "You withdrew $" << amount << " from savings account number " << bo[number].getAccountNumber();
_getch();
b.MainMenu(bo, num, cAcct);
}
else
{
cout << "Incorrect Input, try again";
_getch();
AccountDeposit(bo, number, num, cAcct);
}
}
void BankClassType::MainMenu(BankClassType bo[], int num, int cAcct)
{
cout << "\nWelcome, here are the current accounts on file:\n" << endl;
for (int i = 0; i < cAcct; i++)
{
cout << i + 1 << "--";
bo[i].PrintAccountInfo();
}
int choice;
BankClassType b;
cout << "Enter number (1-5) of account you wish to make changes\n Enter 6 to add an account\nEnter 7 to exit\n --->";
cin >> choice;
if (choice < 6)
b.AcctOptionsMenu(bo, num, cAcct);
else if (choice == 6)
{
bo[cAcct + 1].SetNewAccountInfo(bo, num, cAcct);
cout << "You have successfully added an account!" << endl;
_getch();
cAcct++;
b.MainMenu(bo, num, cAcct);
}
else if (choice == 7)
{
cout << "You have exited, press any key to continue: ";
_getch();
system("cls");
}
else if(choice > 7)
{
cout << "Not a valid input, press a key to try again: ";
_getch();
system("cls");
MainMenu(bo, num, cAcct);
}
}
void BankClassType::AcctOptionsMenu(BankClassType bo[], int num, int cAcct)
{
char choice;
int check = 0;
int count = 0;
int number;
BankClassType b;
while (check == 0) {
cout << "\t\t\n\n" << "Main Menu";
cout << "\t\n\n" << "Select by letter:";
cout << "\t\n" << "(d) - Deposits";
cout << "\t\n" << "(w) - Withdrawals";
cout << "\t\n" << "(s) - Show Account Information.";
cout << "\t\n" << "(q) - Quit Program.\n\n";
cout << "\t" << "Choice: ";
choice = _getche();
switch (choice) {
case 'd':
case 'D':
system("cls");
cout << "\nChoose Account:\n ";
for (int i = 0; i < cAcct; i++) cout << i +1 << "---" << bo[i].getAccountNumber()<< "\n\n" ;
cin >> number;
bo[number].AccountDeposit(bo,number, num, cAcct);
system("cls");
break;
case 'w':
case 'W':
system("cls");
cout << "\nChoose Account:\n ";
for (int i = 0; i < cAcct; i++) cout << i + 1<< "---" << bo[i].getAccountNumber() << "\n\n";
cin >> number;
bo[number].AccountWithdrawal(bo, number, num, cAcct);
system("cls");
break;
case 's':
case 'S':
system("cls");
cout << "\nChoose Account:\n ";
for (int i = 0; i < cAcct; i++) cout << i + 1 << "---" << bo[i].getAccountNumber() << "\n\n";
cin >> number;
bo[number].PrintAccountInfo();
_getche();
system("cls");
break;
case 'q':
case 'Q':
check = 1;
break;
default:
cout << "\nInvalid selection. Press a key to return to main menu.";
_getche();
}
if (check == 1)
break;
}
}
It looks like the array allocated in main is too short. You allocate a block of 4 elements, pass '3' as the cAcct, then bo[cAcct + 1] = bo3. The index will be 4 which is one pass the end of the array. Results are undefined and a crash is likely

Error in file handling using classes?

The code goes like this:
class student
{
char name[20];
int roll;
float marks;
public:
void getdata(void)
{
char ch;
cin.get(ch);
cout << "Name : ";
cin.getline(name, 20);
cout << "\nRoll no : ";
cin >> roll;
cout << "\nMarks : ";
cin >> marks;
cout << "\n";
}
void display(void)
{
cout << "\n" << name << " ,roll no " << roll << " has " << marks
<< "% marks.\n";
}
int getroll()
{ return roll; }
};
void main()
{
clrscr();
student s1;
fstream fil;
int rn;
char ans = 'y';
fil.open("stu.dat", ios::out);
while (ans == 'y')
{
s1.getdata();
fil.write((char *)&s1, sizeof(s1));
cout << "\n Do you want to enter more records :?";
cin >> ans;
}
fil.close();
fil.open("stu.dat", ios::in);
fil.seekg(0);
while (fil)
{
fil.read((char *)&s1, sizeof(s1));
s1.display();
}
fil.close();
getch();
}
The program is about to read and write details of a student using classes.
error
The output shows the details twice if i enter the details once.
output found
nitin, rollno 12 has 98% marks.
nitin, rollno 12 has 98% marks.
output expected
nitin, rollno 12 has 98% marks.
Try this :
class student
{
char name[20];
int roll;
float marks;
public:
void getdata(void)
{
char ch;
cin.get(ch);
cout << "Name : ";
cin.getline(name, 20);
cout << "\nRoll no : ";
cin >> roll;
cout << "\nMarks : ";
cin >> marks;
cout << "\n";
}
void display(void)
{
cout << "\n" << name << " ,roll no " << roll << " has " << marks
<< "% marks.\n";
}
int getroll()
{ return roll; }
};
void main()
{
clrscr();
student s1;
fstream fil;
int rn;
char ans = 'y';
fil.open("stu.dat", ios::out);
while (ans == 'y')
{
s1.getdata();
fil.write((char *)&s1, sizeof(s1));
cout << "\n Do you want to enter more records :?";
cin >> ans;
}
fil.close();
fil.open("stu.dat", ios::in);
fil.seekg(0);
while (fil)
{
fil.read((char *)&s1, sizeof(s1));
if (feof(fil)) {
puts ("End-of-File reached.");
break;
}
s1.display();
}
fil.close();
getch();
}

Crashing after reading with cin

For some reason the program always crashes the second time I main calls inputHolding() and tries to get the call number (the call number is entered and then it crashes). How do I fix this crash? Here is a picture of the call stack and where it is crashing in my code: http://i.imgur.com/zWJ17NC.png
#include <iostream>
#include "LibraryDrv.h"
using namespace std;
int main() {
Holding *hptr[5];
for (int i = 0; i < 5; i++) {
hptr[i] = inputHolding();
}
for (int i = 0; i < 5; i++) {
hptr[i]->print();
}
return 0;
}
Holding* inputHolding() {
char selection;
char title[50];
int callNumber = 0;
char author[50];
char performer[50];
char format;
cout << "Enter B for book, R for recording: ";
cin >> selection;
if (selection == 'B') {
cout << "Enter book title: ";
cin >> title;
cout << "Enter book author: ";
cin >> author;
cout << "Enter call number: ";
cin >> callNumber;
Book* aBook = new Book(title, callNumber, author);
return aBook;
}
else if (selection == 'R') {
cout << "Enter recording title: ";
cin >> title;
cout << "Enter performer: ";
cin >> performer;
cout << "Enter format: (M)P3, (W)AV, (A)IFF: ";
cin >> format;
cout << "Enter call number: ";
cin >> callNumber;
Recording* aRecording = new Recording(title, callNumber, performer, format);
return aRecording;
}
else {
cout << "Incorrect selection" << endl;
return nullptr;
}
}