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
Related
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){
};
A basic student database using classes, I accept
name,
roll number, and
sgpa(cgpa equivalent but out of 10).
I used while loop, and switch case,but if the code for sgpa validation, and code for displaying all students with same sgpa is removed, the program works neatly, but if not, the program goes into continuous loop, the while loop inside the main, as it accepts the options itself and keeps doing it.
The code fails when i accept the sgpa(while taking the student data) or call the displaySGPA fucntion(option 3)
int totalStudents=0;
class database{
float sgpa;
int roll;
string name;
public:
void getSGPA();
void getData(database []);
friend void displaySGPA(int,database []);
};
//Display Students with same SGPA
void displaySGPA(int temp,database students[]){
int i,sameSGPA=0;
for(i=0;i<totalStudents;i++){
if(students[i].sgpa==temp){
sameSGPA+=1;
}
}
if(sameSGPA>1){
cout<<"\nStudents with SGPA "<<temp<<"."<<endl;
for(i=0;i<totalStudents;i++){
if(students[i].sgpa==temp){
cout<<" "<<students[i].roll<<" "<<students[i].name;
}
}
}
else if(sameSGPA==1){
cout<<"Only one student with the SGPA , "<<temp<<". :"<<endl;
for(i=0;i<totalStudents;i++){
if(students[i].sgpa==temp){
cout<<" "<<students[i].roll<<" "<<students[i].name;
break;
}
}
}
else{
cout<<"No Student with given SGPA."<<endl;
}
}
void database :: getData(database students []){
cout<<"\nEnter Name : ";
cin>>name;
cout<<"Enter Roll. ";
cin>>roll;
getSGPA();
}
//SGPA validation
void database :: getSGPA(){
int x=1,temp;
while(x==1){
cout<<"Enter SGPA : ";
cin>>temp;
if(temp<=10){
sgpa=temp;
break;
}
else{
cout<<"Please enter a valid SGPA.";
}
}
}
//main Loop
int main() {
int x,temp;
database students[50];
while (x!=5){
cout<<"\n1.Enter a New Student.\n3.Display students with same SGPA.\n5.Exit.\n\nYour Choice : ";
cin>>x;
switch(x){
case 1:
students[totalStudents].getData(students);
totalStudents++;
break;
case 3:
cout<<"\nEnter the SGPA.";
cin>>temp;
displaySGPA(temp,students);
break;
case 5:
cout<<"Exiting the program.....";
break;
default:
cout<<"Please select a valid option."<<endl;
}
}
}
I found the bug, it was a type conversion bug, i was accepting a float value but passing it as a int,just worked, don't know why.But thanks for each comment and suggestion.
My teacher wanted me to make a program based on An Employee which includes -
His Name
His Id
His Sallary
and we needed to make this using - Structures & Functions & Array as we are not that good in C++ so we just make simple programs . the code of the program i made is below , [ http://pastebin.com/9UFFJseN ]
#include<iostream.h>
#include<conio.h>
#include<dos.h>
#include<process.h>
#include<stdio.h>
struct employee
{
char empname[40];
int empid,empsalary;
}; employee e1;
void add_record(void);
void display_record(void);
void search_record(void);
void welcome();
void exito();
void main()
{
clrscr();
int choice,id;
cout<<"Welcome to Employee Info Menu by Rohit Jalan \n\n\n";
cout<<"1 -> Add Record\n";
cout<<"2 -> Display Record\n";
cout<<"3 -> Search Record\n";
cout<<"4 -> Exit";
cout<<"\n\t\t --> ";
cin>>choice;
switch(choice)
{
case 1: add_record();break;
case 2: display_record();break;
case 3: search_record();break;
case 4: exito();
}
getch();
}
void add_record()
{
clrscr();
cout<<"You have pressed 1\n\n\n";
cout<<"Please enter employee name : ";
gets(e1.empname);
cout<<"Please enter the employee id : ";
cin>>e1.empid;
cout<<"Please enter the employee salary : ";
cin>>e1.empsalary;
cout<<" \n \n \n \n";
main();
}
void display_record()
{clrscr();
cout<<"\nEmployee Name is : ";
puts(e1.empname);
cout<<"\nEmployee ID is : ";
cout<<e1.empid;
cout<<"\nEmployee salary is : ";
cout<<e1.empsalary;
getch();
main();
}
void search_record()
{int id;
clrscr();
cout<<"Please enter the id of the employee\n: ";
cin>>id;
if(id==e1.empid)
{
display_record();
}
else cout<<"\nRecord not found...";
getch();
main();
}
void exito()
{clrscr();
cout<<"\n\n\n\n\t\t\t Thank you. ";
cout<<"\n\n\n\n\n\n\t\t\t Program by \n\n\n";
cout<<"\t\t\t";
delay(500);cout<<"ROHIT";
delay(500);cout<<" JALAN";
cout<<"\n\t\t\t";
delay(500);cout<<"Roll No";
delay(500);cout<<" 11436";
cout<<"\n\t\t\t";
delay(500);cout<<"Class";
delay(500);cout<<" XI-D";
delay(500);cout<<"....";
delay(100);
exit(0);
}
And now my teacher is asking me what if she wishes to enter more then 1 record of data and display more then 1 , or you can say she wants to decide that how much she wants to enter and display , as i am unable to solve her problem i request you all guys to help me in a simple and easy manner as i`m newbie out here . Please don't delay in answer i have a practical examination on 27th Feb 2015 . if you are unable to see my coding -
http://pastebin.com/9UFFJseN#
Thanks In Advance .
In order to perform actions more than once, you need a loop.
unsigned int Display_Menu(void)
{
unsigned int selection = 0;
while (selection != 4)
{
static const char menu_text[] =
"\n"
"Welcome to Employee Info Menu by Rohit Jalan \n\n\n"
"1 -> Add Record\n"
"2 -> Display Record\n"
"3 -> Search Record\n"
"4 -> Exit\n"
"\t\t --> ";
cout.write(menu_text, sizeof(menu_text) - 1);
cin >> selection;
if ((selection >= 1) && (selection <= 4))
{
break;
}
cout << "\nInvalid selection, try again.\n";
}
return selection;
}
The above function displays a menu and if the User enters an invalid choice, it will print the menu again. After a valid choice is received, the function returns to the caller.
This is an example of doing something more than once.
So if your instructor wants to perform more than one action, how would you do it?
Edit 1:
In general a Menu consists of two pieces: 1) Displaying the selections and 2) Processing the choices. The above code handles the displaying of the selections.
// Forward declarations
void Add_Record(void);
void Display_Record(void);
void Search_Record(void);
void Process_Choices(void)
{
unsigned int choice = 0;
do
{
choice = Display_Menu();
switch (choice)
{
case 1: Add_Record(); break;
case 2: Display_Record(); break;
case 3: Search_Record(); break;
}
} while (choice != 4);
}
The above function displays the menu, calls functions according to the User's selection and repeats. It ends when the User enters the number 4.
Again, notice the loop construct that is used for performing actions more than once.
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.
i've been thinking how to do this "save to file" thing all night, but it seems that luck wasnt on my side.. .
I am new to this, and i want to get learned, thats all.
I am from Bulgaria, and for those who wonder what is "edinen", this is your citizen number as a member of that country. (I still dont know how to explain this...)
Here is what I've got
(I've already included the "fstream", but i still dont know how to use it!
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
#define n 30
int num=0;
struct uslugi
{
char name[30];
char surname[30];
char lastname[30];
char illness[30];
long int edinen;
}grupa[n];
void add_record();
void show_record();
void search_record();
void remove_record();
void add_record() // FUNCTION - ADD RECORD(S)
{
system("title Add Record");
int br;
cout<<"\n How many pacients do you want to enter?";
cout<<"\n >> ";
cin>>br;
for(int i=num;i<num+br;i++)
{
cout<<"\n \t\t ENTERING DATA FOR PACIENT NUMBER - "<<i+1<<endl;
cout<<"\n Name:";
cout<<"\n >> ";
cin>>grupa[i].Name;
cout<<"\n Surname:";
cout<<"\n >> ";
cin>>grupa[i].surname;
cout<<"\n Lastname:";
cout<<"\n >> ";
cin>>grupa[i].lastname;
cout<<"\n edinen:";
cout<<"\n >> ";
cin>>grupa[i].edinen;
cout<<"\n Ill from:";
cout<<"\n >> ";
cin>>grupa[i].illness;
}
num=num+br;
}
void show_record() // FUNCTION - SHOW RECORD(S)
{
if (num==0)
{
cout<<"\t\t by far there are no pacient at all \n";
}
cout<<"\n \t\t\t list with all pacients"<<num<<endl;
for(int i=0;i<num;i++)
{
cout<<"\n Name:";
cout<<"\n >> "<<grupa[i].name;
cout<<"\n Surname:";
cout<<"\n >> "<<grupa[i].surname;
cout<<"\n Lastname:";
cout<<"\n >> "<<grupa[i].lastname;
cout<<"\n edinen:";
cout<<"\n >> "<<grupa[i].edinen;
cout<<"\n Ill from:";
cout<<"\n >> "<<grupa[i].illness;
cout<<"\n\n";
}
}
void remove_record() // FUNCTION - DELETE RECORD(S)
{
int k,index;
for(int i=0;i<num;i++)
{
cout<<"\n("<<i+1<<") "<<endl;
cout<<"Pacient name: "<<grupa[i].name<<endl;
cout<<"Surname: "<<grupa[i].surname<<endl;
cout<<"Lastname: "<<grupa[i].lastname<<endl;
cout<<"edinen: "<<grupa[i].edinen<<endl;
cout<<"Ill from: "<<grupa[i].illness<<endl<<endl;
}
cout<<"Who do you want to delete? \n >> ";
cin>>index;
for(k=0;k<num;k++)
{
if(k>=index)
{
grupa[k].edinen=grupa[k+1].edinen;
}
if(k==num-1)
break;
else
cout<<"BY FAR THERE IS NO DATA HERE"<<endl;
}
num--;
for (i=0;i<num;i++)
{
cout<<"Pacient name: "<<grupa[i].name<<endl;
cout<<"Surname: "<<grupa[i].surname<<endl;
cout<<"Lastname: "<<grupa[i].lastname<<endl;
cout<<"edinen: "<<grupa[i].edinen<<endl;
cout<<"Ill from: "<<grupa[i].illness<<endl<<endl;
}
}
void print_count() // FUNCTION - PRINTING
{
cout<<"\n \t\t\t NUMBER OF PACIENTS - "<<num<<endl;
cout<<""<<endl;
}
void search_record() // FUNCTION - SEARCHING
{
int flag=0;
long int tempegn;
cout<<"\n Type the edinen for the pacient you search: ";
cout<<"\n >> ";
cin>>tempegn;
for (int i=0;i<n;i++)
if(tempegn==grupa[i].edinen)
{
cout<<"Pacient name: "<<grupa[i].name<<endl;
cout<<"Surname: "<<grupa[i].surname<<endl;
cout<<"Lastname: "<<grupa[i].lastname<<endl;
cout<<"edinen: "<<grupa[i].edinen<<endl;
cout<<"Ill from: "<<grupa[i].illness<<endl<<endl;
flag++;
}
if (!flag)
{
cout<<"\n\t PACIENT WITH THAT NAME DOESNT EXCIST \n\n";
}
}
void main() // MAIN FUNCTION (MENU)
{
int choice;
do
{
cout<<"\n\t\t******************* Menu *******************"<<endl;
cout<<"\t\t* *";
cout<<"\n\t\t* 1.Add new pacient *";
cout<<"\n\t\t* 2.Search for a pacient by edinen *";
cout<<"\n\t\t* 3.Delete pacient *";
cout<<"\n\t\t* 4.List with all pacients *";
cout<<"\n\t\t* 5.Exit *";
cout<<"\n\t\t* *\n";
cout<<"\t\t************************************************"<<endl;
cout<<"\n Type your choice! ";
cout<<"\n >> ";
cin>>choice;
switch(choice)
{
case 1:{print_count();add_record();break;}
case 2:{print_count();search_record();break;}
case 3:{print_count();remove_record();break;}
case 4:{print_count();show_record();}
}
}
while(choice!=5);
}
I would suggest you read a book, or at least some documentation about this. Also, to understand how this kind of input works, it is required knowledge of oop concepts. As far as I noticed you do not have such a knowledge, I would suggest you stick for a while with procedural i/o functions from C, like fprintf. A google search will show many resources about them and they are pretty easy to understand, at least compared with those from C++, like the ones you are using.
To answer to your question, I will try to explain how to achive what you want. Note that this is a very simplified explanation and not 100% accurate.
Firstly, you need to open the file and create a i/o stream, using ifstream for input files or ofstrsam for output files:
ifstream f("input_filename");
ofstream g("output_filename);
After you created f and/or g (they are not both requied. Also, f and g are just random names) you can use them in the same way you use cin and cout, in this case, as f is for input, it should be used like cin.