C++ File processing and pointers using a class Create a class that tracks locati
ID: 3875840 • Letter: C
Question
C++
File processing and pointers using a class
Create a class that tracks locations and their distances.
The class will need
two constructors,
a default constructor,
a constructor that takes parameters to both fields.
an update routine that takes passed values and updates them
a display routine that sends output to cout.
In your main program create an array of pointers to class objects that you create in heap.
Read in data and update the array with an address to a class object
After the data is read in then walk the array and invoke the display routine.
The input file, Locations.txt is given below:
Locations.txt
Los Angeles 50
San Francisco 32
San Diego 15
Sacramento 12
San Jose 9
If you have the address of a class object (aka a pointer) and you want to call a method remember ptr->method();
You need to be using ‘new’ to allocate the class objects out of heap.
Sample runs:
Place: Los Angeles Distance: 50
Place: San Francisco: 32
Place: San Diego Distance: 15
Place: Sacramento Distance: 12
Place: San Jose Distance: 9
Press any key to continue
Make the location name a char array in your class, not a string.
To set a char array variable to the value in a string:
strcpy(myCharArray,myString.data());
Make sure to comment all of your work!
Explanation / Answer
#include<iostream>
#include<string>
#include<conio>
#include<fstream>
class Locations
{
char loc[30];
int distance;
public :
Locations()
{
strcpy(loc,"NULL");
distance=0;
}
Locations(char aloc[30],int dist)
{
strcpy(loc,aloc);
distance=dist;
}
void update(char aloc[30],int dist)
{
strcpy(loc,aloc);
distance=dist;
}
void display()
{
cout<<" Place : "<<loc;
cout<<" Distance : "<<distance<<endl;
}
};
void main()
{
clrscr();
char aloc[30];
int dist;
Locations * arr = new Locations[10];
ifstream fin;
fin.open("Locations.txt");
for(int i=0;i<5;i++)
{
fin>>aloc;
fin>>dist;
arr[i]->update(aloc,dist);
}
for(i=0;i<5;i++)
{
arr[i]->display();
}
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.