好的,所以我在理解指针方面遇到了很多困难,而且我已经达到了需要一点指导的地步。这是我到目前为止编写的代码:
#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++;
}
}
这个想法是创建一个动态分配的结构数组,并传递一个指针,该指针可以指向数组的每个元素到两个函数。这编译成功,但因为我没有完全得到它的语法,它并没有很好地结束。
主要问题在于getdata函数我敢肯定。每次我尝试纠正它,我认为它应该是我得到语法错误。有人可以说明如何正确地改变指针指向数组中每个元素的值吗?
提前非常感谢!
答案 0 :(得分:1)
Dustin,我喜欢你编写程序的方式,这是理解使用指针和结构的概念的最简单方法。我在你的代码中看到的唯一错误是,虽然你已经创建了一个结构数组你的main函数并将它传递给populate,但你在getdata()和dispdata()函数中将结构检索为“结构数组”时犯了一个错误。因此,如果你必须使这个代码片段成为工作代码片段,你需要根据索引访问结构数组.eg“Airports * p [1] where 30”。
所以有两种修复你的代码的方法 1.传递单个结构而不是发送结构数组。 2.将整个结构数组传递给getdata和dispdata函数,并在结构集周围循环,为每个结构赋值或显示值(Airports * p)。
答案 1 :(得分:1)
在displaydata()
函数中,您必须删除p++
,因为您也在递增索引i
,因此每次迭代,您实际上正在读取第二个下一个元素(在第0个元素之后,您将从数组中读取第2个,然后是第4个,因此您将超过数组绑定。
此外,在您的getdata()
方法中,由于getline()
跟随cin
(来自上一次迭代),因此cin
未读取的换行符将被视为getline()
的下一个输入。要避免此问题,请将cin.get()
放在循环的末尾。
因此,您需要进行2次更改:
void getdata(Airports *p)
{
for (int i = 0; i < 3; i++)
{
cout << "Enter the name of airport " << i+1 << ": ";
// ... skipping ...
cin >> p->runway;
cout << endl;
cin.get(); // put this line to "absorb" the unwanted newline
p++;
}
void dispdata(Airports *p)
{
// ... skipping ...
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++; // remove this line, for reason described in the answer
}
}
此外,请避免使用system("PAUSE");
出于此处讨论的原因:system("pause"); - Why is it wrong?而是使用cin.get()
或getchar()