Repeat statement for switch case - c++

So I want make the program that can input data many times, for example I choose case 1 again after I use case 1 to input data. Or I choose case 2 many times to see all data as I want.
Mostly said break statement bring the solution. But, when I using break statement after case, the program was terminated. So how I can make repeat switch statement without make terminating program?
If I make this, the switch case happen sequentially. Example, I can input case 1 normally but when I input case 1 again it will go to next case instead case 1 and vice versa until exit case. This is my source code:
#include <iostream>
#pragma hdrstop
using namespace std;
struct ig
{
int id;
string name;
ig *next;
ig *prev;
};
ig *head= NULL;
ig *tail= NULL;
//---------------------------------------------------------------------------
int main(int argc, char** argv)
{
cout<<"+---------------------------------------+"<<endl;
cout<<"| Instagram User Data |"<<endl;
cout<<"+---------------------------------------+"<<endl;
cout<<"|1. Add Instagram ID |"<<endl;
cout<<"|2. Look All Data |"<<endl;
cout<<"|3. Look Previous Data |"<<endl;
cout<<"|4. Look Next Data |"<<endl;
cout<<"|5. Exit |"<<endl;
cout<<"+---------------------------------------+"<<endl;
int choose,l;
cout<<"your choices (1/2/3/4/5): ";cin>>choose;
switch(choose)
{
case 1:
{
cout<<"Input limit : ";cin>>l;
for(int a=1;a<=l;a++)
{
ig *new= new ig;
new->next=NULL;
new->prev=NULL;
cout<<"Entry Number : ";cin>>new->id;
cout<<"Instagram ID : ";cin>>new->name;
cout<<"===================="<<endl;
if(head== NULL)
{
head=new;
tail=new;
}
else
{
new->prev=tail;
tail->next=new;
tail=new;
}
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 2:
{
while(head!= NULL)
{
cout<<head->id<<endl;
cout<<head->name<<endl;
head=head->next;
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 3:
{
if(tail=NULL)
{
ig *show;
show=head;
while(show!= NULL)
{
cout<<head->id<<endl;
cout<<head->name<<endl;
head=head->prev;
}
}
else
{
cout<<"Data belum terisi"<<endl;
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 4:
{
ig *show;
show=tail;
while(show!= NULL)
{
cout<<tail->id<<endl;
cout<<tail->name<<endl;
tail=tail->next;
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 5:
{
return 0;
}
}
}
I tried to learn the logic of statement and the solution many times, but still unsuccessful. So I need help here, thank you

Put a while around the switch:
while (true) {
int choose = askChoice();
switch (choose)
{
case 1: AddInstagramID(); break;
case 2: LookAllData(); break;
case 3: LookPreviousData(); break;
case 4: LookNextData(); break;
case 5: return 0;
}
}

Related

Stack using arrays

If suppose i want to implement a stack in c++ using arrrays is it better to do it via making a structure or class for storing the location of head and stuff like that or should you implement in more of a hard code style like this -
#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
Im just trying to know what is a more accepted method.
The approach you've taken here using global variables is fine for a simple implementation, but it has a major drawback in most real-world applications: it's not reusable.
What if you need two stacks in your program? That would require creating a second set of global variables and a second set of functions to act on them.
That is the problem that using a class solves. If you wrap all of your stack's state in a class then you can create a single set of functions that can operate on any object of that class. Then creating a second stack is very simple.
Of course, for most real world applications you shouldn't implement your own stack anyway. Just use std::stack unless you have a very compelling reason not to. But that still supports the same conclusion. Because std::stack is a self-contained, reusable class any program can use it without having to re-implement their own stack logic (possibly multiple times).

how to replace a value of a variable inside code from user input?

i am trying to add a developer mode in my program. since duty of car defers every month,i want give my user permission to change every single variables in my program alike duty lccost yen2taka freight
#include <iostream>
using namespace std;
class A
{
public:
int carbid,duty;
void Input()
{
cout<<"please insert the car price you want to bid for(in yen): ";
cin>>carbid;
cout<<"duty of the car: ";
cin>>duty;
}
int Exportcost()
{
int exportcost;
int servicechrg=10;
int freight=20;
exportcost=servicechrg+freight+carbid;
return exportcost;
}
int Yen2taka()
{
int yen2taka;
int taka2dollarrate=10;
int dollar2yen=1;
yen2taka=((Exportcost())/dollar2yen)*taka2dollarrate;
return yen2taka;
}
int Importcost()
{
int importcost;
int lccost=10;
int cnfcost=20;
importcost=lccost+cnfcost;
return importcost;
}
int Totalcosting()
{
int total;
int myprofit=10; //80000
total=myprofit+Importcost()+Yen2taka();
cout<<total;
return total;
}
void summary()
{
cout<<
}
};
int main()
{
x:
A ob;
ob.Input();
ob.Exportcost();
ob.Yen2taka();
ob.Importcost();
ob.Totalcosting();
int ch;
cout<<"press 1 to see the summery of the costing or 2 to restart costing again"<<endl;
cin>>ch;
switch(ch)
{
case 1:
ob.summary();
break;
case 2:
goto x;
}
}
At first, you should collect these parameters in a separate class:
class Configuration // maybe you find a better name...
{
int m_servicechrg = 10; // default
int m_freight = 20;
// ...
public:
int servicechrg() { return m_servicechrg; }
void servicechrg(int value); { /* check some limits? */ m_servicechrg = value; }
int freight() { return m_freight; }
void freight(int value); { /* check some limits? */ m_freight = value; }
// ...
};
// will allow you to do:
// C c; std::cout << c;
ostream& operator<<(ostream& s, Configuration const& c)
{
// which ever formatting is appropriate...
s << c.servicechrg() << ' ' << c.freight();
return s;
}
The setters could alternatively return bool to indicate invalid values.
Now you can use this class within main:
Configuration c;
A a;
int cost = a.exportCost(c); // you'd have to adjust signatures...
int value;
switch(ch)
{
case 4:
if(stc::cin >> freight) // catches invalid user input!
// one ALWAYS should do, otherwise you might end up in
// your program not working any more
{
c.freight(value);
// or, if you have:
if(!c.freight(value))
{
// some appropriate error message
// (it's better not to output in the setter, you are more flexible this
// way – maybe you want different messages at different occasions?)
}
}
else
{
// appropriate error handling
}
break;
default:
// handling invalid user input
// again, you always should; but stream state is not in error state,
// so you just can print appropriate error message
break;
}
See this answer for how to correctly handle stream errors.
If you wonder about the differences in error handling: First case is met if user enters non-numerical input, such as ss, second case, if input is numerical, but out of valid range (77).
Now if you don't want to pass the configuration as parameter all the time, you could make a global variable from (but careful, there are some dangers with global variables, use them as sparely as possible) or implement the singleton pattern.
Side notes: goto can be a fine tool sometimes, but it is a dangerous one (and the label's name x isn't a good one, prefer a name that clearly shows intention, such as REENTRY_POINT, LOOP_START, ...). If you can get along without unreasonable effort, prefer such variants:
bool isRunning = true;
do
{
// ...
case 2:
isRunning = false;
break;
}
while(isRunning);
Sure, an additional variable, an additional check; unfortunately, you cannot use break to exit a (pseudo-) endless loop (for(;;)) (but don't apply this pattern for nested loops, then it gets more and more unreadabla – and ineffcient: bool isExit = false; for(int i = 0; !isExit && i < n; ++i) { for(j = 0; j < n; ++j) { isExit = true; break; } } – see what I mean?). A variant might be:
for(;;)
{
switch(ch)
case 1:
// ...
//break; <- replace
continue;
case 2:
//
break;
} // end of switch
break; // break the surrounding for(;;) loop
}
But that's not really nice either.
A pretty nice variant allowing to exit the loop in the given case, as there isn't anyhting to do afterwards:
for(;;)
{
switch(ch)
{
case 2:
// maybe yet some cleaning up here
return 0;
default:
// ...
break;
}
}
Drawback: The function's exit point possibly is deeply nested inside the code.
There are yet other tricks to allow this pattern, like packing sub-sections of code in a lambda having a return inside and call that one directly. But that now really starts going beyond the scope...
Finally, if you insist on goto, my variant would rather be:
for(;;)
{
switch(ch)
{
case 2:
// ...
goto LOOP_EXIT;
default:
// ...
break;
}
}
LOOP_EXIT:
return 0; // e. g. main
(void)0; // if there isn't anything to do in the function any more
// (labels require an instruction afterwards!)
There won't be a hidden loop now and it is more obvious what you actually are doing. Currently, not really an issue, but if your code grows, the hidden loop gets more and more difficult to spot.
In such cases, I clearly mark the gotos so that another coder can immediately spot the critical code points:
///////////////////////////////////////////////////
// possibly some comment why applying this pattern
goto SOME_LABEL;
///////////////////////////////////////////////////
One could do the same with deeply nested function exit points (return).

C++ values not reading in while loop switch case

All functions have be declared public in my .header file
this is my code:
void menu
{
int option = 0;
//cout menu here//
//getting user input to enter their option of menu
cin>>option;
menuChoice(option);
}
void menuChoice(int option)
{
int kiv = 0;
const int size = 50;
while(option) //option just an int to get input from a menu
{
switch(option)
{
case 1: {
while(kiv<size)
{
//codes here to read user inputs then entry increment
++kiv;
}
//cout<<kiv<<endl; // doesn't work here too , it displays nothing
}break;
case2:{
cout<<kiv<<endl; // displays 0
}break;
}
}
}
i have declared the kiv on top , then increment it in the while loop , however the value stays in the while(option) loop so when i go to case 2 , it suppose to print out the incremented value , but it display 0 , am i going in the correct direction?
This may be the one you looking for
int kiv = 0;
const int size = 50;
void menuChoice(int option);
void getOption()
{
int option = 0;
cin >> option;
menuChoice(option);
}
void menuChoice(int option)
{
switch (option) {
case 1:
while (kiv < size) {
//codes here to read user inputs then entry increment
++kiv;
}
//cout<<kiv<<endl; // doesn't work here too , it displays nothing
break;
case 2:
cout << kiv << endl; // displays 0
break;
}
getOption();
}
void menu()
{
//cout menu here//
//getting user input to enter their option of menu
getOption();
}
int main(int argc, char **argv)
{
menu();
return 0;
}
It's not entirely clear from your example, but I am guessing that each time you process a menuChoice you enter that function, and as a result you re-initialised kiv back to 0 each time.
If that is the case, you probably need to change the type of kiv to
static int kiv = 0;
This will cause kiv to retain its value between invocations.

C++ Array of Struct: Functions aren't working [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 8 years ago.
Improve this question
Hey guys I'm pretty new into coding...
so my code won't run and i don't know what is wrong.
one of the errors that Im getting is that in my
void animal::petDataInfo(animal maxEntry[], int counter)
the counter is saying that it isn't being initialized...
basically i don't know whats wrong....
animal.h
#ifndef Database_animal_h
#define Database_animal_h
struct animal
{
char petName[20];
char lastName[30];
char color[12];
int month, day, year;
void petDataInfo(animal [], int &counter);
void displayInfo(animal [], int &counter);
}; animal maxEntry[100];
#endif
main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "animal.h"
enum animalSpecies {Dog, Cat, Bird, Reptile, Other};
animalSpecies getAnimal();
void print(animalSpecies entered);
void menuInfo(animal [], int &counter);
void petDataInfo(animal [], int &counter);
void displayInfo(animal [], int &counter);
void quitInfo(int &counter);
int main()
{
int counter=0;
counter++;
menuInfo(maxEntry, counter);
system ("PAUSE");
return 0;
}
/********************************************************************************************************/
void menuInfo(animal maxEntry[], int& counter)
{
char letter;
do
{
cout<<"\nWhat would you like to do?"<<endl;
cout<<"(E)nter"<<endl;
cout<<"(S)earch"<<endl;
cout<<"(D)isplay"<<endl;
cout<<"(C)lear"<<endl;
cout<<"(Q)uit"<<endl;
cout<<"\n";
cout<<"Please enter a letter: "<<endl;
cin>>letter;
cout<<"\n";
cout<<"\n";
if (!((letter=='e')|| (letter=='E') || (letter=='s') || (letter=='S') || (letter=='d') || (letter=='D') || (letter=='c') || (letter=='C') || (letter=='q') || (letter=='Q')))
{
cout<<"Not a valid letter. Try again."<<endl;
cout<<"\n";
}
}
while (!((letter=='e')|| (letter=='E') || (letter=='s') || (letter=='S') || (letter=='d') || (letter=='D') || (letter=='c') || (letter=='C') || (letter=='q') || (letter=='Q')));
{
switch (letter)
{
case'e': case 'E':
petDataInfo(maxEntry, counter);
if ((letter=='e') || (letter=='E'))
{
cout<<"Entry number: "<<counter++;
}
break;
case 's': case 'S':
cout<<"goes to search database"<<endl;
break;
case 'd': case 'D':
displayInfo(maxEntry, counter);
break;
case 'c': case 'C':
if ((letter=='c') || (letter=='C'))
{
counter--;
}
break;
case 'q': case 'Q':
quitInfo(counter);
break;
default:
cout<<"Try again. \n";
}
}
}
/********************************************************************************************************/
void animal::petDataInfo(animal maxEntry[], int counter)
{
for(int i=0; i<counter; i++)
{
cout<<"What is the pets first name? "<<endl;
cin>>maxEntry[i].petName;
cout<<"What is the owners last name? "<<endl;
cin>>maxEntry[i].lastName;
getAnimal();
cout<<"What month is your pets date of birth? "<<endl;
cin>>maxEntry[i].month;
cout<<"What day is your pets date of birth? "<<endl;
cin>>maxEntry[i].day;
cout<<"What year is your pets date of birth? "<<endl;
cin>>maxEntry[i].year;
cout<<"What color is your pet? "<<endl;
cin>>maxEntry[i].color;
}
menuInfo(maxEntry, counter);
}
/********************************************************************************************************/
animalSpecies getAnimal()
{
animalSpecies entered = Dog;
char species;
cout<<"Species of Animal:\n (D)og\n (C)at\n (B)ird\n (R)eptile\n (O)ther\n "<<endl;
cin>>species;
switch (species)
{
case 'd':
case 'D':
entered = Dog;
break;
case 'c':
case 'C':
entered = Cat;
break;
case 'b':
case 'B':
entered = Bird;
break;
case 'r':
case 'R':
entered = Reptile;
break;
case 'o':
case 'O':
entered = Other;
break;
default:
cout<<"Error: Try again. "<<endl;
}
return entered;
}
/********************************************************************************************************/
void print(animalSpecies entered)
{
switch (entered)
{
case Dog:
cout<<"Dog"<<endl;
break;
case Cat:
cout<<"Cat"<<endl;
break;
case Bird:
cout<<"Bird"<<endl;
break;
case Reptile:
cout<<"Reptile"<<endl;
break;
case Other:
cout<<"Other"<<endl;
break;
}
}
/********************************************************************************************************/
void animal::displayInfo(animal maxEntry[], counter)
{
for(int i=0; i<100; i++)
{
cout<<"Pet name: "<<maxEntry[i].petName<<"\n";
cout<<"Owners last name: "<<maxEntry[i].lastName<<"\n";
cout<<"Pet species: ";
animalSpecies entered;
entered = getAnimal();
print(entered);
cout<<"Pets DOB: ";
if (month<10)
{
cout<<"0"<<maxEntry[i].month<<"/"; //if month is less than 10 it will add a '0' in front
}
else
{
cout<<maxEntry[i].month<<"/";
}
if (day<10)
{
cout<<"0"<<maxEntry[i].day<<"/";
}
else
{
cout<<maxEntry[i].day<<"/";
}
cout<<maxEntry[i].year<<"\n";
menuInfo(maxEntry, counter); //goes back to the menu
}
}
/********************************************************************************************************/
void quitInfo(int& counter)
{
int ans;
do
{
cout<<"Are you sure you want to quit? (y/n)"<<endl;
cin>>ans;
if ((ans=='n') || (ans=='N'))
{
menuInfo(maxEntry, counter); //goes back to the menu function
}
else if ((ans=='y') || (ans=='Y'))
{
exit(0); //exits the program
}
else
{
cout<<"Error: Try again. "<<endl;
}
}
while (!(ans=='n') || !(ans=='N') || !(ans=='y') || !(ans=='Y'));
}
Issues I found in your code:
You have declared petDataInfo and displayInfo in two places, once inside the definition of animal and once in main.cpp. Looking at your code, I don't think you need them inside animal.
You are missing the type of counter in the definition of displayInfo.
void animal::displayInfo(animal maxEntry[], counter)
You need to add the type in that line. Also, since the function is not a member function of animal, it can be written as:
void displayInfo(animal maxEntry[], int& counter)
The type of counter is different in the declaration and the definition of petDataInfo. I the declaration, you are using int& counter. In the definition, you are using int counter. Make sure that they match. Also, the class scope can be removed from the definition since it's no longer a member function of animal.
void petDataInfo(animal maxEntry[], int& counter)
You are missing the object when trying to access the month and day. Change the line
if (month<10)
to
if (maxEntry[i].month<10)
and change
if (day<10)
to
if (maxEntry[i].day<10)
I haven't verified the logic of your program. If there are any, hopefully you can track and fix them.

In my program what is the difference between Record* and Databse*?

I am using Dev C++ compiler.
So, what's wrong in here, i am getting errors in the addRecord Module.
The compile log :
Compiler: Default compiler
Executing g++.exe...
g++.exe "C:\SAI,MANI\test_add(09.03.2013).cpp" -o "C:\Users\Ravitheja\Desktop\C and C++\Projects\SAI,MANI\test_add(09.03.2013).exe" -O3 -g3
-I"C:\Dev-Cpp\lib\gcc\mingw32\3.4.2\include" -I"C:\Dev-Cpp\include\c++\3.4.2\backward" -I"C:\Dev-Cpp\include\c++\3.4.2\mingw32" -I"C:\Dev-Cpp\include\c++\3.4.2" -I"C:\Dev-Cpp\include" -L"C:\Dev-Cpp\lib" -g3
C:\SAI,MANI\test_add(09.03.2013).cpp: In function `void addRecord(Record*)':
C:\SAI,MANI\test_add(09.03.2013).cpp:151: error: using typedef-name `Record' after `struct'
C:\SAI,MANI\test_add(09.03.2013).cpp:151: error: cannot convert `Record*' to `Database*' in assignment
C:\SAI,MANI\test_add(09.03.2013).cpp:153: error: expected primary-expression before '*' token
C:\SAI,MANI\test_add(09.03.2013).cpp:153: error: expected primary-expression before ')' token
C:\SAI,MANI\test_add(09.03.2013).cpp:153: error: expected `;' before "malloc"
C:\SAI,MANI\test_add(09.03.2013).cpp:154: error: cannot convert `Record*' to `Database*' in assignment
C:\SAI,MANI\test_add(09.03.2013).cpp: In function `void viewRecords(Record*)':
C:\SAI,MANI\test_add(09.03.2013).cpp:180: error: cannot convert `Database*' to `Record*' in assignment
C:\SAI,MANI\test_add(09.03.2013).cpp: In function `int getDate(date*)':
C:SAI,MANI\test_add(09.03.2013).cpp:187: error: conversion from `date*' to non-scalar type `date' requested
Execution terminated
particularly in this line ,
x->next = (Record*)malloc(sizeof(struct Record));
i am getting an error : cannot convert 'Record*' to ' Database*' in assignment, but what is the difference between Record and Database, as i have typedef-ed them.
I have not written all the modules yet, i just wanted to test my addRecord() and viewRecords() , but it's not working. How to correct these errors ?
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
using namespace std;
// global declarations and function prototypes....
const int TRUE = 1,FALSE = 0,SUCCESS = 1;
const int SUBJECTS = 3;
typedef char String[25];
// date structure , a better way to store dates.
struct date
{
int day,month,year;
};
// Database structure , the main double linked list which stores all the information.
typedef struct DataBase
{
String Name,FatherName,Address,Hometown;
float Marks[SUBJECTS],Total,Percentage;
date DOB;
long int RegNo,PhoneNumber;
struct Database *previous; // the addresses of the next and previous nodes in the dll.
struct Database *next;
}Record;
int main();
int menu(); // for displaying menu.
void process(int,Record*); // for processing the menu.
void addRecord(Record*); // for adding a record.
void delRecord(Record*); // for deleting a record.
void modRecord(Record*); // for modifying values of a record.
void sortRecords(Record*); // for sorting records.
void filterRecords(Record*); // for filtering records.
void searchRecords(Record*); // for searching a record.
void viewRecords(Record*); // for viewing records (all).
int getDate(date*); // for getting input for a date.
void copyDate(date,date*); // for copying two date variables.
int checkDate(date); // for checking wether a given date is correct.
char *toString(int); // for displaying month name given the month number.
void copyRecord(Record*,Record*); // for copying contents of one record into another.
// main function...
int main()
{
Record *r;
r = (Record*) malloc (sizeof(Record));
r->next = NULL;
r->previous = NULL;
while(1)
{
process(menu(),r);
}
}
// the menu function.
int menu()
{
static int choice;
cout<<"\n\t\t\t Menu";
cout<<"\n\t\t\t 1.Add Records ";
cout<<"\n\t\t\t 2.Delete Records";
cout<<"\n\t\t\t 3.Modify Records";
cout<<"\n\t\t\t 4.Sort Records";
cout<<"\n\t\t\t 5.Filter Records";
cout<<"\n\t\t\t 6.Search Records";
cout<<"\n\t\t\t 7.View Records";
cout<<"\n\t\t\t 8.Exit";
cout<<"\n\t\t\t YOUR CHOICE : ";
cin>>choice;
if(choice>=1 && choice<=7) return choice;
else if(choice == 8) exit(0);
else
{
cout<<"\n Sorry, that's an invalid choice.";
cout<<"\n Please Try Again.";
menu();
}
}
void process(int choice,Record *r)
{
switch(choice)
{
case 1:
addRecord(r);
break;
case 2:
delRecord(r);
break;
case 3:
modRecord(r);
break;
case 4:
sortRecords(r);
break;
case 5:
filterRecords(r);
break;
case 6:
searchRecords(r);
break;
case 7:
viewRecords(r);
break;
}
}
void addRecord(Record *x)
{
date *t;
t = (date*) malloc ( sizeof(date) );
fflush(stdin);
Record *temp; temp = (Record*) malloc ( sizeof(Record) );
cout<<"\n Enter the following details ..... "<<endl;
cout<<"\n Name : ";
gets(temp->Name);
cout<<"\n Father's Name : ";
gets(temp->FatherName);
cout<<"\n Address :";
gets(temp->Address);
cout<<"\n Hometown : ";
gets(temp->Hometown);
cout<<"\n Register Number : ";
cin>>temp->RegNo;
temp->Total = 0;
for(int i=0;i<SUBJECTS;i++)
{
cin>>temp->Marks[i];
temp->Total += temp->Marks[i];
}
temp->Percentage = temp->Total/SUBJECTS;
cout<<"\n Total Marks : "<<temp->Total;
cout<<"\n\n Percentage : "<<temp->Percentage;
if(getDate(t) == SUCCESS) // trick!
copyDate(temp->DOB,t);
x->next = (Record*)malloc(sizeof(struct Record));
copyRecord(x,temp);
temp->previous = (Record*)malloc(struct Database);
temp->previous = x;
temp->next = NULL;
return;
}
void viewRecords(Record *x)
{
if(x->next == NULL && x->previous == NULL)
{
cout<<"\n There are no records to view.";
cout<<"\n Please Add some records and then try again!";
return;
}
do
{
cout<<"\n Name : "<<x->Name;
cout<<"\n Father's Name : "<<x->FatherName;
cout<<"\n Address : "<<x->Address;
cout<<"\n Hometown : "<<x->Hometown;
cout<<"\n Register Number : "<<x->RegNo;
for(int i=0;i<SUBJECTS;i++)
cout<<"\n Mark "<<i+1<<" : "<<x->Marks[i];
cout<<"\n Total Marks : "<<x->Total<<endl;
cout<<"\n Percentage : "<<x->Percentage;
cout<<"\n Date Of Birth : "<<x->DOB.day<<"th"<<toString(x->DOB.month)<<" "<<x->DOB.year;
if(x->next == NULL) break;
}while((x=x->next)!=NULL);
}
int getDate(date *t)
{
cout<<"\nDate of birth (dd:mm:yyyy) : ";
scanf("%d:%d:%d",&t->day,&t->month,&t->year);
if(checkDate(t) == SUCCESS)
return SUCCESS;
else
{
cout<<"\n Sorry, that's not a valid Date.";
cout<<"\n Please Try Again,"<<endl;
getDate(t);
}
}
void copyDate(date d1,date *d2)
{
d1.day = d2->day;
d1.month = d2->month;
d1.year = d2->year;
return;
}
int checkDate(date *x)
{
int leap = (x->year%4==0)?TRUE:FALSE;
if( ( x->day<=0 || x->day > 31 ) || (x->month>12 || x->month<=0) || (x->year<1900 || x->year > 2008) )
return FALSE;
else if(leap == TRUE && x->month == 2 && (x->day>29))
return FALSE;
else if(leap == FALSE && x->month == 2 && (x->day>28))
return FALSE;
else if( (x->month == 4 || x->month == 6 || x->month == 9 || x->month == 11) && x->month >= 31 )
return FALSE;
else
return TRUE;
}
char *toString(int m)
{
char *t = (char*) malloc (sizeof(char)*4);
switch(m)
{
case 1 : t = "Jan"; break;
case 2 : t = "Feb"; break;
case 3 : t = "Mar"; break;
case 4 : t = "Apr"; break;
case 5 : t = "May"; break;
case 6 : t = "Jun"; break;
case 7 : t = "Jul"; break;
case 8 : t = "Aug"; break;
case 9 : t = "Sep"; break;
case 10 : t = "Oct"; break;
case 11 : t = "Nov"; break;
case 12 : t = "Dec"; break;
}
return t;
}
I think the root of the problem is that Record is a typedef name for struct Database, and the first error (using the struct keyword with Record) is leading to the later errors.
Since this is C++, dump malloc entirely and use the new operator:
x->next = new Record;
You don't need to use struct keyword for typedef..
so,
x->next = (Record*)malloc(sizeof(struct Record));
should be
x->next = (Record*)malloc(sizeof(Record));
Note:
You better use new instead of malloc
You should make up your mind whether you want to write C or C++, as they are different languages.
The answer to your main question, "what is the difference between Record and Database", is that
typedef struct Database
{
// ...
} Record;
introduces several names for the struct.
In C there would be two: struct Database and Record.
In C++, such as your code, there are three: the same two as in C, plus just Database.
In neither language is there a type called struct Record, which is why you get the first error: "using typedef-name 'Record' after 'struct'".
You should always fix the first error first.
(I'm not sure if this would fix your problem as your g++ lokks a bit dated - if it's really version 3.4.2 it's almost 10 years old and you should consider upgrading).