Dynamic allocating an object - c++

Here is my code, I was trying to allocate memory to an object by asking size from the user. I dont know where I am going wrong. The error the compiler is giving me is "void value not ignored as it ought to be". Please help me. Thanks in advance.
#include <iostream>
using namespace std;
class test
{
char name[20];
char address[30];
char desig[20];
public:
void getData();
void display();
~test()
{
cout << "Destructor is invoked";
}
};
void test::getData()
{
cout << "Enter your name" << endl;
cin >> name;
cout << "Enter address" << endl;
cin >> address;
cout << "Enter designation" << endl;
cin >> desig;
}
void test::display()
{
cout << "name" << endl;
cout << name << endl;
cout << "address" << endl;
cout << address;
cout << "Enter designation" << endl;
cout << desig;
}
int main()
{
int s;
cout << "Enter the size of an array" << endl;
cin >> s;
test* p1 = new test[s];
for (int i = 0; i < s; i++)
{
*p1[i].getData();
}
for (int i = 0; i < s; i++)
{
*p1[i].display();
}
delete[] p1;
return 0;
}

You need to change:
*p1[i]
To:
p1[i]

Here:
*p1[i].display();
You're calling member function display that returns void and try to dereference that.

Related

Writing from file to class

Making a project I have to write patient database and I have a problem. Looking through guids in iтternet I dont understand how to read from file to class and how to write class into file(I realized it using common input, it is better to rewrite it).
And I dont understand how to make base constructor for char, like with int
point()
{
x=y=z=0;
}
need like
Patient()
{
name="Mike";
surename="Smith";
adress="New York";
ilness="Cold"
card_number=1;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int add();
int read();
string path = "base.txt";
class Patient
{
private:
char *name;
char *surename;
char *adress;
char *ilness;
int *card_number;
public:
void set()
{
cout << "Enter name:";
cin >> name;
cout << "Enter surename:";
cin >> surename;
cout << "Enter adress:";
cin >> adress;
cout << "Enter diagnosis:";
cin >> ilness;
cout << "Enter card number:";
cin >> *card_number;
}
void show()
{
cout << "Name:" << name << endl;
cout << "Surename:" << surename << endl;
cout << "Adress:" << adress << endl;
cout << "Cardnumber:" << card_number << endl;
cout << "Diagnosis:" << ilness << endl;
}
void print()
{
cout << name << surename << adress << ilness << card_number << endl;
}
Patient()
{
}
Patient(const char* s)
{
int length = 0;
while (s[length++] != ' ')
;
name = new char[length];
for (int i = 0; i < length; i++)
name[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
surename = new char[length];
for (int i = 0; i < length; i++)
surename[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
adress = new char[length];
for (int i = 0; i < length; i++)
adress[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
ilness = new char[length];
for (int i = 0; i < length; i++)
ilness[i] = s[i];
length = 0;
while (s[length++] != '\n')
;
card_number = new int[length];
for (int i = 0; i < length; i++)
card_number[i] = s[i];
}
};
int main()
{
char a;
cout << "Choose the action:" << endl;
cout << "a. Add new patient" << endl;
cout << "b. Delete patient" << endl;
cout << "c. Find for card number" << endl;
cout << "d. Find for ilnesses" << endl;
cin >> a;
switch (a)
{
case 'a':
add();
break;
case 'b':
read();
break;
default:
cout << "error" << endl;
}
system("pause");
return 0;
}
int add()
{
fstream file;
file.open(path, fstream::out | fstream::in | ofstream::app);
if (!file.is_open())
{
cout << "Error" << endl;
}
else
{
string str;
cout << "Opend" << endl;
cout << "Enter name" << endl;
cin >> str;
file << str<<" ";
cout << "Enter surename" << endl;
cin >> str;
file << str << " ";
cout << "Enter adress" << endl;
cin >> str;
file << str << " ";
cout << "Enter ilness" << endl;
cin >> str;
file << str << " ";
cout << "Enter card number" << endl;
cin >> str;
file << str<<"\n";
cout << "Sucsesfully added\n";
}
file.close();
return 0;
}
int read()
{
fstream file;
file.open(path, fstream::out | fstream::in | ofstream::app);
if (!file.is_open())
{
cout << "Error" << endl;
}
else
{
cout << "Opend" << endl;
string str;
Patient first;
while (file.read((char*)&first,sizeof(Patient)))
{
first.print();
}
}
file.close();
return 0;
}
Database example
Mike Smith New_York Cold 1
Charles Williams London Flu 2
Henry Roberts York Coronovirus 3
Robert Garcia Sydney Cold 4
methods how to write from file to class and from class to file
If you want to serialise your data structures, it's best to use a library and data format, such as JSON.
Personally, I recommend nlohmann::json because of it's ease of use and flexibility.
Overloading the constructor and serialising data
Overloading your constructor is nothing other than overloading another method in C++.
If your class is Patient:
#include <string>
#include <nlohmann/json.hpp>
using nlohmann::json;
using std::string; // Don't use using namespace std;!
class Patient {
public:
Patient() = default;
explicit Patient(const string& name, const string& surname,
const string& addr, const string& illness):
m_name(name), m_surname(surname), m_address(addr), m_illness(illness) {}
explicit Patient(const json& data) { fromJson(data); }
virtual ~Patient() = default;
json toJson() const {
return {
{ "Name", m_name },
{ "Surname", m_surname },
{ "Address", m_address },
{ "Illness", m_illness }
};
}
void fromJson(const json& data) {
if (data.contains("Name") && data["Name"].is_string()) {
m_name = data["Name"].get<string>();
} // and so on
}
void dumpJson(const string& filePath) const {
ofstream out(path, std::ios::out);
// error checking
out << filePath;
}
private: // members
string m_name;
string m_surname;
string m_address;
string m_illness;
};
I haven't tested this code and won't guarantee it will work first try, but it should point you in the right direction. This code requires at least C++11.

Why am I getting strange values for integer in this example of derived class (C++)

I was given a task to write an example of derived class. But In my program, something strange is happening with the roll numbers.
Also, when this program is compiled in g++.
When I used char [] and gets() to store the strings and input values into them, it didn't allow me to enter the value for collname.
When I use string and cin, I get some strange values while asking for marks.(Check the attached image).
#include<iostream>
#include<conio.h>
using namespace std;
class uni
{
private:
int rollno[100], i, flag;
int intermarks[100];;
int theorymarks[100];
void settheorymarks();
protected:
int numstud;
void setintermarks();
void issurno();
public:
void prepres();
void showres(string collname);
};
class college : public uni
{
private:
string collname;
public:
college(int N)
{
numstud = N;
issurno();
}
void enter_marks();
void disp();
};
void uni::issurno()
{
for (i = 0; i < numstud; i++)
rollno[i] = 1024+i;
cout << "Roll numbers issued!" << endl;
}
void uni::settheorymarks()
{
cout << "Enter theory marks for: " << endl ;
for(i = 0; i < numstud; i++)
{
cout << i+1 << ".) Roll number: " << rollno << " : ";
cin >> theorymarks[i];
}
cout << endl << endl << "Theory marks recorded!" << endl;
}
void uni::setintermarks()
{
cout << "Enter inter marks for: " << endl ;
for(i = 0; i < numstud; i++)
{
cout << i+1 << ".) Roll number: " << rollno << " : ";
cin >> intermarks[i];
}
cout << endl << endl << "Internal marks recorded!" << endl;
}
void uni::prepres()
{
settheorymarks();
}
void uni::showres(string colnam)
{
cout << "College: " << colnam << endl;
cout << "__________________________Result___________________________" << endl;
cout << "s. No.\tRoll no\tInternal\tTheory" << endl;
for(i = 0; i < numstud; i++)
cout << i+1 << "\t" << rollno[i] << '\t' << intermarks[i] << "\t" << theorymarks[i] << endl;
cout << endl << "End of result!" << endl;
}
void college::disp()
{
showres(collname);
}
void college::enter_marks()
{
cout << "Enter the college name: ";
cin >> collname;
setintermarks();
prepres();
}
int main()
{
int n;
cout << "Enter number of stufents: ";
cin >> n;
college c(n);
c.enter_marks();
c.disp();
return 0;
}
I feel that I've made a stupid mistake somewhere.
PS: In school, I was forced to use turbo C++ (One of the oldest compilers).
You just forget the [i] after rollno in the two lines like:
cout << i+1 << ".) Roll number: " << rollno[i] << " : ";
There are a few other things I would ask you to improve if I was your supervisor/teacher:
always use expressive variable and method names. Avoid any abbreviations.
why is there the arbitray offset of 1024 in rollno? If this is just "obfuscation" remove it...
Unclear: why is setintermarks called inside enter_marks but settheorymarks in prepres ?
typo in "stufents"

qualified-id in declaration before '(' token

This is some crazy error and is giving me a lot of trouble.
#include <iostream>
using namespace std;
class Book {
private:
int bookid;
char bookname[50];
char authorname[50];
float cost;
public:
void getinfo(void) {
for (int i = 0; i < 5; i++) {
cout << "Enter Book ID" <<endl;
cin >> bookid;
cout << "Enter Book Name" << endl;
cin >> bookname;
cout << "Enter Author Name" << endl;
cin >> authorname;
cout << "Enter Cost" << endl;
cin >> cost;
}
}
void displayinfo(void);
};
int main()
{
Book bk[5];
for (int i = 0; i < 5; i++) {
bk[i].getinfo();
}
void Book::displayinfo() {
for(int i = 0; i < 5; i++) {
cout << bk[i].bookid;
cout << bk[i].bookname;
cout << bk[i].authorname;
cout << bk[i].cost;
}
}
return 0;
}
The error, as noted in the title is expected declaration before '}' token at the line void Book::displayinfo() in main
Also this error is coming expected '}' at end of input
Move the function definition void Book::displayinfo(){} out of the main().
Along with this, i have some more suggestion for you. Update your class definition like this
class Book{
private:
int bookid;
string bookname; // char bookname[50]; because it can accept book name length more than 50 character.
string authorname; // char authorname[50]; because it can accept authorname length more than 50 character.
float cost;
public:
void getinfo(void){
for(int i =0; i < 5; i++){
cout << "Enter Book ID" <<endl;
cin >> bookid;
cout << "Enter Book Name" << endl;
getline(cin,bookname); // Because book name can have spaces.
cout << "Enter Author Name" << endl;
getline(cin,authorname); // Because author name can have spaces too.
cout << "Enter Cost" << endl;
cin >> cost;
}
}
void displayinfo(void);
};

Debug Assertion Failed String!=NULL C++

I've created a class patient that contains some information about patients such as Name, Age, Adress etc.
When I try to compile the program I get an
Debug Assertion Failed (Expression String != NULL) and I can't seem to find why is this happening.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class pacient{
protected:
int colesterol;
int tensiune_arteriala;
char * nume;
char * prenume;
int varsta;
char * adresa;
char * data_analiza;
public:
//constructor cu toti parametrii
pacient(){};
pacient(int colesterol, int tensiune_art, char * nume, char *prenume,
int varsta, char * adresa, char *data_analiza)
{
(*this).colesterol = colesterol;
tensiune_arteriala = tensiune_art;
strcpy((*this).nume, nume);
strcpy((*this).prenume, prenume);
(*this).varsta = varsta;
strcpy((*this).adresa, adresa);
strcpy((*this).data_analiza, data_analiza);
}
//destructor
~pacient(){
colesterol = 0;
tensiune_arteriala = 0;
strcpy(nume, "");
strcpy(prenume, "");
varsta = 0;
strcpy(adresa, "");
strcpy(data_analiza, "");
}
//functie virtuala
virtual char * get_name() { return "Este pacient"; }
//citirea si afisarea obiectelor
friend istream &operator>> (istream&in, pacient&ob);
friend ostream &operator<< (ostream&out, const pacient&ob);
};
istream& operator>>(istream &in, pacient &ob){
cout << "Nume: "; gets(ob.nume); cout << endl;
cout << "Prenume: "; gets(ob.prenume); cout << endl;
cout << "Varsta: "; cin >> ob.varsta; cout << endl;
cout << "Adresa: "; gets(ob.adresa); cout << endl;
cout << "Data analiza: "; gets(ob.data_analiza); cout << endl;
cout << "Colesterol: "; cin>>ob.colesterol; cout << endl;
cout << "Tensiune arteriala: "; cin>>ob.tensiune_arteriala; cout << endl;
return in;
}
ostream &operator<< (ostream&out, const pacient&ob){
cout << "Nume: "; puts(ob.nume); cout << endl;
cout << "Prenume: "; puts(ob.prenume); cout << endl;
cout << "Varsta: "; cout << ob.varsta; cout << endl;
cout << "Adresa: "; puts(ob.adresa); cout << endl;
cout << "Data analiza: "; puts(ob.data_analiza); cout << endl;
cout << "Colesterol: "; cout << ob.colesterol; cout << endl;
cout << "Tensiune arteriala: "; cout << ob.tensiune_arteriala; cout << endl;
return out;
}
int main()
{
pacient a;
cin >> a;
cout << a;
}
That's because you have members that are pointers:
char * nume;
char * prenume;
...
But you don't initalize them, and don't allocate memory, but netvertheless try to use them:
pacient(int colesterol, int tensiune_art, char * nume, char *prenume,
int varsta, char * adresa, char *data_analiza)
{
...
strcpy((*this).nume, nume); ///<======= OUCH !!!!
Consider using string instead of char*:
you won't have to manage memory, it's automatic
you can use = instead of strcpy
you can return string without having to worry about leaking memory

How to add a name field for a shop database (OOP/C++)

Ok, so I've made a database type program and created an item number and price field. I've also tried to stick to a primary key by using the index values of the array of both the "item number" field and "price". But was wondering how to add an "Item name" field along with this to make it work. I've tried to think of many different ways of adding a char type array but that doesn't really work.
#include<iostream>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the price of the item: ";
cin >> price[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Price: " << price[i] << endl << endl;
}
}
void main()
{
class shop s;
s.input();
s.output();
}
Create a class or struct to hold the data:
struct Item
{
int id;
float price; // float may lead to rounding errors.
// I would use int and store cents
//string name;
// If you really want to use c-style string
char name[20];
// or
// char *name; // You would need to use new with this
};
Then keep an array of these:
class shop
{
private:
Item items[20];
// As mentioned, better than a static array would be a vector
//std::vector<Item> items;
public:
void input();
void output();
};
What about a vector of strings?
#include<iostream>
#include <string>
#include <vector>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
vector<string> names;
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
names.resize(n);
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the price of the item: ";
cin >> price[i];
cout << "Enter the name of the item: ";
cin >> names[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Price: " << price[i] << endl << endl;
cout << "Name: " << names[i] << endl << endl;
}
}
And it would be good to have a destructor to clean the memory taken by the vector.
I would use std::string
#include <iostream>
#include <string>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
string name[20];
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the name of the item: ";
cin >> name[i];
cout << "Enter the price of the item: ";
cin >> price[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Item Name: " << name[i] << endl;
cout << "Price: " << price[i] << endl << endl;
}
}
int main()
{
class shop s;
s.input();
s.output();
}