C++指针和结构

C++ Pointer and Structure

本文关键字:结构 指针 C++      更新时间:2023-10-16

我必须完成以下任务:

  1. 读取文件person.txt中有关个人的信息(请参阅下文)并存储到数组p中。首先将每个人的配偶指针设置为NULL
  2. MaryTom执行合并操作。你可以通过将两个人的配偶指针设置为指向对方(对方的商店地址)来结婚
  3. 打印出数组p中的内容,其中需要打印数组p所指向的每个人变量。如果个人配偶指针为NULL值,则打印Not Married,否则打印配偶姓名。程序的输出如下所示。确保你的输出是一样的

我可以做(1),读取文本文件person.txt,其中包含以下内容:

Mary        012-35678905    20000
John        010-87630221    16000
Alice       012-90028765    9000
Tom         019-76239028    30000
Pam         017-32237609    32000

但是我不知道怎么做(2)和(3)。

这是我迄今为止所做的,基于问题提供的模板,我不应该改变:

#include <iostream>    //>>>>>>> This part is the template given >>>>>>>
#include <cstdlib>     //
#include <fstream>     //
//
using namespace std;   //
//
struct person          //
{                      //
char name[30];         //
char phone[15];        //
double money;          //
person *spouse;        //
};                     //
//
int main()             //
{                      //
person *p[10];         //<<<<<<<< This is the end of the template part <<<  
ifstream inFile;
inFile.open("person.txt");
if (inFile.fail())
{
cout << "Error in opening the file!" << endl;
exit(1);
}
char name[30], phone[15];
int money;
int number = 5;
for (int i = 0; i < number; i++)
{
inFile >> name >> phone >> money;
cout << "Name:" << name << endl;
cout << "Phone:" << phone << endl;
cout << "Money:" << money << endl;
cout << "Spouse Name:" << endl;
cout << endl;
}
cin.get();
system("pause");
return 0;
}

预期输出应该是这样的:

Name: Mary
Phone Number:012-35678905
Money: 20000
Spouse Name:Tom
Name: John
Phone Number:010-87630221
Money: 16000
Spouse Name: Not Married
...

请注意,此练习显示了C的过时使用++

首先是您有点忘记使用的数组p。CCD_ 11是一个10的数组。但是10个呢?person*的指针也是如此。

这是非常老式的C++。如果你在网上学习课程,请立即更改,因为现在我们会使用vector<person>stringnullptr。如果这是一门课堂课程,你别无选择,所以让我们继续…

一些提示,基于你已经做过的事情

首先简化读取循环,不要忘记按照问题中的要求将指针设置为NULL:

for (int i = 0; i < number; i++)
{
person *r = new person;                     // allocate a new person 
inFile >> r->name >> r->phone >> r->money;  // read data into the new person
r->spouse = NULL;                           // initialize the poitner
p[i] = r;                                   // store the pointer in the array 
}

你几乎已经有了打印部分(3)。你只需要把它从你的阅读循环移到一个新的循环,从数组中打印出来,并处理已婚人士的特殊情况:

for (int i = 0; i < number; i++)
{
cout << "Name:" << p[i]->name << endl;
cout << "Phone:" << p[i]->phone << endl;
cout << "Money:" << p[i]->money << endl;
cout << "Spouse:" ;
if (p[i]->spouse==NULL) {
cout << "Not married" <<endl; 
}
else {
cout << p[i]->spouse->name <<endl; 
}
cout << endl;
}

现在自己做点什么

现在是关于玛丽和汤姆在(2)结婚的事。这更微妙。我不会为你做这件事,因为现在你已经拥有了完成家庭作业所需的一切。但总的原则是:

  • 创建两个指针spouse1spouse2,并将它们初始化为NULL
  • 循环遍历数组,找出哪个人是Tom,哪个是Marry,并更新相关指针(例如spouse1 = p[i];)
  • 在循环的最后,检查我们是否找到了配偶双方(两个指针都不再为NULL,而且两个指针不同,因为你不能嫁给有自我的人)
  • 如果可以的话,就嫁给他们吧:spouse1->spouse=spouse2; spouse2->spouse=spouse1;

最后,在结束程序之前,您需要释放数组中的所有指针(使用向量,您不必关心这一点)。

需要进一步改进

你仍然需要改进你的阅读循环,使其更有活力。因为实际上,您不知道文本文件中有多少行。因此,从number=0开始,尽可能长时间地读取数据,每次递增number,但如果无法再读取,或者达到阵列的最大大小,则停止。