Why the binary file can't be created? - c++

I'm trying to create a program that in the main() function enters to a menu using a switch. In each case invoques another functions. In the function createFile(), which it is supposed to create a binary file, fill it out with 0's and then add the info that is required in the first space is returning (1) and it says that the file couldn't be created. What am I doing wrong? What was my mistake?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct athletesInfo
{
int heartRate;
int time;
};
void createFile(fstream&);
void addInfo(fstream&);
void showInfo(fstream&);
int n;
int main(){
int op;
fstream fileA;
do
{
cout<<"MENU"<<endl;
cout<<"(1) Enter the first Heart Rate of an Athlete"<<endl;
cout<<"(2) Add Another Athlete"<<endl;
cout<<"(3) Show Info Athletes"<<endl;
cout<<"(4) Exit"<<endl;
cout<<"Choose an option: ";
cin>>op;
switch (op)
{
case 1:
createFile(fileA);
break;
case 2:
addInfo(fileA);
break;
case 3:
showInfo(fileA);
break;
default:
cout<<"Choose a correct option."<<endl;
break;
}
} while (op!=4);
return 0;
}
void createFile(fstream &fileA){
athletesInfo athle;
fileA.open("athletes.dat", ios::in|ios::out|ios::binary);
if (fileA.fail())
{
cout<<"The file couldn't be created"<<endl;
exit(1);
}
cout<<"How many registers would you like?"<<endl;
cin>>n;
for (int i = 0; i < n; i++)
{
fileA.seekg(i* sizeof(athletesInfo));
athle.heartRate=0;
athle.time= 0000;
fileA.write((char *)&athle, sizeof(athletesInfo));
}
cout<<"Enter the info of the first athlete"<<endl;
cout<<"Heart rate: ";
cin>>athle.heartRate;
cout<<"Time (00:00): ";
cin>>athle.time;
while (athle.heartRate<0 && athle.time>2359 && athle.time<0000)
{
cout<<"Wrong Inputs."<<endl;
cout<<"Enter the info of the first athlete"<<endl;
cout<<"Heart rate: ";
cin>>athle.heartRate;
cout<<"Time (00:00): ";
cin>>athle.time;
}
fileA.write((char *)&athle, sizeof(athletesInfo));
fileA.close();
}
void addInfo(fstream& fileAthletes){
};
void showInfo(fstream& fileAthletes){
};

Related

How to add a value to an already full array without using std::copy to make a new one

I'm trying to develop a program that, in case 2, after an array has been "filled" it adds another space so you are able to add another value to your original array. I tried my best but failed miserably. I cannot use std::copy to just copy the array and add it to a new one with more space in it. Any help is appreciated, thanks!
#include <iostream>
#include <string>
using namespace std;
void stampa (string x[], int q){ //Cout all inserted names
int i;
cout<<"Your names are: "<<endl;
for (i=0; i<q; i++){
cout<<x[i]<<endl;
}
}
void carica(string x[], int q){ //Function to insert the names
int i;
for(i=0; i<q; i++){
cout<<"Insert the "<<i+1<<" name:"<<endl;
cin>>x[i];
}
}
void controllo (int &x){ //Error if a negative number is inserted
while (x<=0) {cout<<"Error! Insert a positive number:"<<endl;
cin>>x;
}
}
int main(){
int scelta, n;
string nome;
bool exit=false;
cout<<"How many names do you want to enter?"<<endl;
cin>>n;
controllo(n);
string a[n];
carica(a,n);
do{
system("cls");
cout<<"1) Print your names"<<endl;
cout<<"2) Insert a new name"<<endl;
cout<<"3) Exit"<<endl<<endl;
cin>>scelta;
switch (scelta){
case 1:
stampa(a,n);
system("pause");
break;
case 2:
cout << "Enter new name to insert: " << endl;
cout<<"Done!"<<endl;
system("pause");
break;
case 3:
exit=true;
cout<<"Goodbye!"<<endl;
break;
}
}while (!exit);
system("pause");
}
Try using std::vector instead of a simple array, or create an array through pointers.
vector: https://www.youtube.com/watch?v=Jh2urtP00Zg
Pointers: https://www.programiz.com/cpp-programming/memory-management

How do I loop in this if / else program

the question asks me to repeat this program until users enter X. what should I do to loop this program? should I use while?
question: repeat the program until the user enter X for package code
#include <iostream>
using namespace std;
int main(){
int price_package;
char package_code;
int num;
int no_of_adults;
int no_of_childs;
cout<<"Enter package code: ";
cin>>package_code;
if(package_code=='A'){
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
price_package= ((40*no_of_adults)+(21*no_of_childs));
cout<<"price package: RM"<<price_package<<endl;
}
else if(package_code=='B'){
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
price_package=((23*no_of_adults)+(14*no_of_childs));
cout<<"price package: RM"<<price_package<<endl;
}
else if(package_code=='C'){
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
price_package=((38*no_of_adults)+(18*no_of_childs));
cout<<"price package: RM"<<price_package<<endl;
}
else{
cout<<"ERROR";
}
}
You could use a while loop or a do while loop. Both of which would look like the following:
// import and variables here
do{
// logic to loop
} while(package_code!='X')
Or
// imports and variables
//declare package_code with some value other than 'X'
while(package_code!='X'){
//loop logic
}
Try this
#include <iostream>
using namespace std;
void Output(int no_of_adults, int no_of_childs, int price_package)
{
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
cout<<"price package: RM"<<price_package<<endl;
}
int main()
{
int price_package;
char package_code;
int num;
int no_of_adults;
int no_of_childs;
while (1)
{
cout<<"Enter package code: ";
cin>>package_code;
if(package_code=='A')
{
price_package= ((40*no_of_adults)+(21*no_of_childs));
Output(no_of_adults, no_of_childs, price_package);
}
else if(package_code=='B')
{
price_package=((23*no_of_adults)+(14*no_of_childs));
Output(no_of_adults, no_of_childs, price_package);
}
else if(package_code=='X')
{
break;
}
else
{
cout<<"ERROR"<<endl;
}
}
}

unable to write to/read from file

The code I wrote seems to work when i write data in the file but when i look into the record.dat file after writing into it, it shows nothing. The segment with "Main Menu" gets repeated from the switch() every time i try to read from the file. I had to write the open commands with the access modes separately inside each case otherwise it wouldn't even open the file.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <conio.h>
using namespace std;
class employee
{
private:
int empcode;
char empname[30];
char empdesig[15];
float empsalary;
public:
void add_rec()
{
cout<<"\nEmployee Code : ";
cin>>empcode;
cout<<"\nEmployee Name : ";
cin.ignore();
cin.getline(empname,30);
cout<<"\nEmployee Designation : ";
cin.getline(empdesig,15);
cout<<"\nEmployee Salary : ";
cin>>empsalary;
}
void read_rec()
{
cout<<"\nEmployee Code : "<<empcode;
cout<<"\nEmployee Name : "<<empname;
cout<<"\nEmployee Designation : "<<empdesig;
cout<<"\nEmployee Salary : "<<empsalary;
}
};
int main()
{
employee emp;
fstream rfile;
int ch,rec_no=0,pos=0;
char ans='y',opt;
do
{
cout<<"\n";
cout<<"\t\t\t MAIN MENU ";
cout<<"\n1. Add Record ";
cout<<"\n2. Read Record ";
cout<<"\n3. Modify Record ";
cout<<"\n4. Exit "<<endl;
cout<<"\nSelect an option : ";
cin>>ch;
switch (ch)
{
case 1:
{
rfile.open("record.dat", ios::out);
char opt='y';
cout<<"\t\t\tEmployee Data Entry "<<endl;
do
{
emp.add_rec();
rfile.write((char*)&emp,sizeof(emp));
cout<<"\nEnter another record ? {Y/N} ";
cin>>opt;
} while(opt=='y'||opt=='Y');
}
break;
case 2:
{
rfile.open("record.dat", ios::in);
cout<<"\t\t\tEmployee Data Display "<<endl;
rfile.read((char*)&emp,sizeof(emp));
while(rfile)
{
emp.read_rec();
rfile.read((char*)&emp,sizeof(emp));
}
}
break;
case 3:
{
rfile.open("record.dat", ios::out);
cout<<"\t\t\tEmployee Data Modify "<<endl;
cout<<"\nEnter the record no. to modify : ";
cin>>rec_no;
pos=(rec_no-1)*sizeof(emp);
rfile.seekg(pos,ios::beg);
rfile.read((char*)&emp,sizeof(emp));
cout<<"\nModify this record ? {Y/N} "<<endl;
cin>>opt;
if(opt=='y'||opt=='Y')
{
cout<<"\n";
cout<<"\t\t\tEnter New Data "<<endl;
emp.add_rec();
rfile.write((char*)&emp,sizeof(emp));
cout<<"\nRecord Modified"<<endl;
cout<<"\nPress any key to continue...";
getch();
}
}
break;
case 4:
break;
default:
cout<<"\nPlease select a valid option!";
break;
}
} while(ch!=4);
rfile.close();
return(0);
}
Each time you open a file for writing under a case statement, you also need to close the file. When the file is closed, the double buffered values are then written to the physical file.
Under case 1, add a file close after the while statement:
} while(opt=='y'||opt=='Y');
rfile.close();
Make similar updates to case 2 and 3, and both case 1 and 2 will now work. Case 3 has additional issues. For example, when opening the file to modify, you will want to use the "app" bit mask so you do not delete existing contents. See the following for more information:
https://en.cppreference.com/w/cpp/io/basic_fstream/open

Program compiles but I think switch is ignored.

I am currently studying c++ but I fell behind a little bit, so I apologize if my question is obvious.
I have to create a program that asks for a student's name, GPA, Year of admission, and get a random 5 digit number generated for that person. The number of students will not exceed 42.
My program compiled (somehow) and I am able to get the error for invalid menu selection, however, whenever I give a valid selection (currently 1) nothing happens.
Maybe I am missing something, this is why I need help.
Here is my code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//print all the menu options
void print_menu()
{
cout<<"\nRCNJ Registrar Menu:"<<"\n"
<<"\n"
<<"[1] Add a student"<<"\n"
<<"[2] Display all students"<<"\n"
<<"[3] Display by year"<<"\n"
<<"[4] Display statistics"<<"\n"
<<"[5] Quit"<<"\n";
}
//get and return the student's name
void get_name(string& student_name) //call student_name after that.
{
cout<<"Please enter the sudent's name: ";
cin >> student_name;
cout<<"\n";
}
//validate and return gpa
double get_gpa()
{
double student_gpa = 0;
cout<<"Please enter the GPA: ";
cin >>student_gpa;
cout<<"\n";
while (student_gpa > 4 || student_gpa < 0)
{
cout<<"Please enter a valid GPA for the student (0.00 - 4.00): ";
cin >> student_gpa;
cout<<"\n";
}
return student_gpa;
}
//validateand return year
int get_year()
{
int student_year = 0;
cout<<"Please enter the year: ";
cin >> student_year;
cout<<"\n";
while (student_year >2016 || student_year <1972)
{
cout<<"Please enter a valid year (min 1972, max 2016): ";
cin >> student_year;
cout<<"\n";
}
return student_year;
}
//generate the student's R#
int generate_number()
{
int r_number;
srand (time(NULL));
r_number = rand() % 89999 + 10000;
return r_number;
}
//save info. Include get_name, get_gpa, get_year
void input_new_student()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int s_name, s_gpa, s_year, r_num;
get_name(student_name);
get_gpa();
get_year();
generate_number();
}
//display all students in the proper format
void print_all()
{
}
//get a year as selection and print all students that are the same year
void print_by_year()
{
}
//display statistics based on entered students
void print_statistics()
{
}
//validate and return the menu option selected by the user.
//it should call print_menu defined earlier
int get_selection(int menu_choice)
{
menu_choice = 0;
cout<<"\n"
<<"Selection: ";
cin >> menu_choice;
cout<<"\n";
while (menu_choice > 5 || menu_choice< 1)
{
cout<<" Menu choice is invalid. Please re-enter (1 - 5): ";
cin>> menu_choice;
cout<<"\n";
}
return menu_choice;
}
int main()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int menu_choice;
int s_name=0;
int s_gpa=0;
int s_year=0;
int r_num=0;
string nameArray[42];
s_name++;
double gpaArray[42];
s_gpa++;
int yearArray[42];
s_year++;
int ramapoArray[42];
r_num++;
print_menu();
get_selection(menu_choice);
switch (menu_choice)
{
case 1:
input_new_student();
nameArray[s_name] = student_name;
gpaArray[s_gpa] = student_gpa;
yearArray[s_year] = student_year;
ramapoArray[r_num] = r_number;
break;
}
return 0;
}
I dont have permission to comment, hence adding it here.
In you main(),
get_selection(menu_choice);
switch (menu_choice)
You return menu_choice, but there is none to take the value, you end you using garbage value as it is uninitialized.
So two ways you can do it, either by passing the address/reference of menu_choice or by return value. try either of these it should work, though I have not gone through the rest of your program.
As suggested by others, try a debugger e.g. gdb?

Program on cricket scoreboard

Why is the following code not giving results and how to get results?
Whenever I run the code, it first asks for the names of the players of two teams playing the match, then it shows the menu from which if we select any one of the option it again asks for the batsman name which is not according to the program designed. My research on the code and the problem is that I think buffer memory is full but I don't know how to free it, any help would be beneficial. Thank you
#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
class scorecard{
char batname[11][20];
int runscored[11];
char situation[11][10];
char mode[11][15];
char bowlername[11][20];
float oversplayed[11];
int maiden[11];
int runsgiven[11];
int wicketstaken[11];
public:
void updatebatsman(void);
void updatebowler(void);
void displaybat(void);
void displaybowl(void);
void menu(void);
scorecard()
{for(int n=0;n<12;n++)
{
runscored[n]={0};
oversplayed[n]={0};
maiden[n]={0};
runsgiven[n]={0};
wicketstaken[n]={0};
}
}
};
int main()
{
int jb=0;
scorecard s1;
int kb;
s1.menu();
do
{
cout<< "Enter the option"<<endl;
cout<<"(1) Display batting score"<<endl<<"(2) Display Bowling score"<<endl<<"(3) Update batting score"<<endl;
cout<<"(4) Update Bowling score"<<endl;
cin >>kb;
switch(kb)
{
case 1 : s1.displaybat();
break;
case 2 :s1.displaybowl();break;
case 3:s1.updatebatsman();break;
case 4:s1.updatebowler();break;
default:cout<<"Wrong choice";
}
}while (jb<1);
}
void scorecard::updatebowler(void)
{char bowlname[20];
int str,k,option,overnumbers,maidenumb,uprun,upwicket;
cout<<"Enter Bowler name:";
cin.getline(bowlname,20);
for( k=0;k<11;k++)
{str= strcmp(bowlername[k],bowlname);
if (str== 0)
{
cout<<"Menu for Bowler information update "<<endl;
cout<<"(1) Update Number of overs"<<endl<<"(2) Update maiden overs"<<endl<<"(3) Update runs given"<<endl;
cout<<"(4) Update wickets taken"<<endl;
cin >> option;
switch(option)
{
case 1:{cout<<"Enter Numbers of overs to be updated:";
cin >>overnumbers;
cout<<endl;
oversplayed[k]+=overnumbers;
break;
}
case 2:{cout <<"Enter the number of maiden overs to be updated:";
cin>>maidenumb;
cout<<endl;
maiden[k]+=maidenumb;
break;
}
case 3:{cout <<"Enter the number of runs to be added:";
cin>>uprun;
cout<<endl;
runsgiven[k]+=uprun;
break;
}
case 4: {cout<<"Enter number of wickets to be updated:";
cin >>upwicket;
cout<<endl;
wicketstaken[k]+=upwicket;
}
default:cout<<"wroung choice";
}
break;
}
}
if (str!=0)
cout <<"You entered wrong player."<<endl;
}
void scorecard::updatebatsman(void)
{char batsmaname[20];
int str,k;
cout<<"Enter Batsman name:";
cin.getline(batsmaname,20);
for( k=0;k<11;k++)
{str= strcmp(batname[k],batsmaname);
if (str== 0)
{
cout<<"enter runs scored:";
cin>>runscored[k];
cout<<endl<<"enter weather out or not out:";
cin>>situation[k];
cout<<endl<<"enter mode(if batsman out) by which batsman was out:";
cin>>mode[k];
break;
}
}
if (str!=0)
cout <<"You entered wrong player."<<endl;
}
void scorecard::displaybat(void)
{
cout << "Batsman name"<<'t'<<"Runs scored"<<'t'<<"situation"<<'t'<<"mode"<<endl;
for(int j=0;j++;j<12)
{
cout<<batname[j]<<'t'<<runscored[j]<<'t'<<situation[j]<<'t'<<mode[j]<<endl;
}
}
void scorecard::displaybowl(void)
{
cout << "Bowler name"<<'t'<<"overs played"<<'t'<<"maiden overs"<<'t'<<"wicket taken"<<'t'<<"Runs given"<<endl;
cout<<endl;
for(int j=0;j++;j<12)
{
cout<<bowlername[j]<<'t'<<oversplayed[j]<<'t'<<maiden[j]<<'t'<<wicketstaken[j]<<'t'<<runsgiven[j]<<endl;
}
}
void scorecard::menu(void)
{
cout<<"Enter the name of players of batting team"<<endl;
for (int k=0;k<11;k++)
{
cout <<"Enter name of player "<<k+1<<":";
cin>>batname[k];
}
cout <<"Enter the name of players of bowling team"<<endl;
for (int n=0;n<11;n++)
{
cout <<"Enter name of player "<<n+1<<":";
cin>>bowlername[n];
}
}
This is very wrong:
for(int j=0;j++;j<12)
It should be:
for(int j=0; j < 11; j++)
You are also missing a break in your case 4 statement for the options:
case 4: {cout<<"Enter number of wickets to be updated:";
cin >>upwicket;
cout<<endl;
wicketstaken[k]+=upwicket;
break;
}
default:cout<<"wroung choice";
Without the break you will see also the output wrong choice when the user selects option 4.