好,所以我在理解指针时遇到很多麻烦,而且我已经达到需要一点指导的地步了。这是我到目前为止编写的代码:
#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函数。每次我尝试将其更正为我认为应该的语法错误。有人可以说明如何正确更改指针在数组的每个元素中指向的值吗?
非常感谢!
在displaydata()
函数中,您将必须删除p++
,因为您还要增加索引i
,因此,每次迭代实际上是在读取第二个下一个元素(在第0个元素之后,您将读取数组的第2个,然后是第4个),因此您将越过数组边界。
[另外,在您的getdata()
方法中,由于getline()
跟随cin
(来自上一次迭代),因此cin
尚未读取的换行符将被视为getline()
的下一个输入。为避免此问题,请将cin.get()
放在循环末尾。
因此,您需要进行两项更改:
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()
[我喜欢您构造程序的方式,这是可以理解将指针与结构一起使用的概念的最简单方法。
我在代码中看到的唯一错误是,尽管您在主函数中创建了一个结构数组并将其传递给填充,但是您在将结构作为“结构数组”检索结构时却犯了一个错误。 getdata()和dispdata()函数。
因此,如果您必须使此代码段有效,则需要基于索引访问结构数组。例如Airports *p[1] where 3<i>0
。
所以有两种固定代码的方法