I’m having a lot of trouble understanding pointers, and I’ve hit a point where I need a little guidance. Here is the code I’ve written so far:
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
//Declare structure
struct Airports{
string name;
string airID;
double elevation;
double runway;};
void dispdata(Airports *);
void getdata(Airports *);
int main()
{
Airports *airptr;
airptr = new Airports [3];
getdata(airptr);
dispdata(airptr);
system ("PAUSE");
return 0;
}
void getdata(Airports *p)
{
for (int i = 0; i < 3; i++)
{
cout << "Enter the name of airport " << i+1 << ": ";
getline(cin, p->name);
cout << "Enter the airport " << i+1 << " identifier: ";
getline(cin, p->airID);
cout << "Enter the elevation for airport " << i+1 << ": ";
cin >> p->elevation;
cout << "Enter the runway length for airport " << i+1 << ": ";
cin >> p->runway;
cout << endl;
p++;
}
cout << "Thanks for entering your values!";
}
void dispdata(Airports *p)
{
cout << "\nHere are the data values you entered:" << endl;
cout << "\n\t\tAirport info" << endl;
cout << "Airport\tAirID\tElevation\tRunway Length" << endl;
cout << "----------------------------------------------------------------" << endl;
cout << fixed << setprecision(2);
for (int i = 0; i<3; i++)
{
cout << p[i].name << "\t" << p[i].airID << "\t" << p[i].elevation << "\t" << p[i].runway << endl;
p++;
}
}
The idea is to create a dynamically allocated array of structures and to pass a pointer that can point to each element of the array to both functions. This compiles successfully, but because I don’t quite get the syntax for this it doesn’t end well.
The main problem lies in the getdata function I’m sure. Every time I try to correct it to how I think it should be I get a syntax error. How can I properly change the value the pointer points to in each element of the array?
In your
displaydata()function, you will have to remove thep++, because you are also incrementing the indexi, thus per iteration, you are actually reading the 2nd next element (after 0th element, you will read 2nd, and then 4th) from the array, and hence you will go past the array bound.Also, in your
getdata()method, since agetline()follows acin(from the previous iteration), the newline character left unread bycinwill be treated as the next input bygetline(). To avoid this problem, putcin.get()at the end of the loop.Hence, you need to make 2 changes:
Also, please avoid using
system("PAUSE");for reasons discussed here: system("pause"); – Why is it wrong? Instead usecin.get()orgetchar()