City Distance coderinme

City Distance coderinme

write a class CITY to represent name of a city and its distance from
Aligarh. The name of city is represented by means of a char pointer for which
exact amount of storage is allocated at run-time through a dynamic constructor.
Include following functions:
1. Default, copy constructors and destructor.
2. A member function setdata () that accepts cityname and distance. It allocates
storage for the name member and assigns data values to the CITY object that
invokes it.
3. A member functions to display the data members.
4. An outside function ncity () that is friend of the CITY class. It accepts an array
of CITY objects and returns one which is nearer to Aligarh.
Write a C++ program to use this class for an array of N=5 city objects.
Solution:

#include<iostream.h>
#include<conio.h>
class city
{
public:
char *cityname;
float dist;
city(){
cityname = NULL;
dist = 0;
}
city(city &r)
{
dist = r.dist;
cityname = r.cityname;
}
void setdata();
void disp();
friend char* ncity(city c);
~city(){
delete [] cityname;
}
};
void city::setdata(){
cityname = new char[30];
fflush(stdin);
//getline(cin, cityname);
cin.getline(cityname,25);
fflush(stdin);
cin>>dist;
}
void city::disp(){
cout<<endl<<"The details entered by your is: "<<cityname<<" "<<dist<<endl<<endl;
}
char* ncity(city c[]){
float f=c[0].dist;
int i;
for(i=0;i<5;i++){
if(c[i].dist<f){
f=c[i].dist;
}
}
for(i=0;i<5;i++){
if(c[i].dist == f){
return(c[i].cityname);
}
}
}
int main(){
city a1[5];
for(int i=0;i<5;i++)
{
fflush(stdin);
cout<<"Enter the "<<i+1<<" city name and city distance from Aligarh:"<<endl;
a1[i].setdata();
a1[i].disp();
}
cout<<"City which is nearer to Aligarh is: "<<ncity(a1)<<endl;
getch();
return 0;
}

For more programs in C++, visit our C++ Coder Archives

City Distance coderinme

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.