【发布时间】:2019-02-10 10:09:18
【问题描述】:
我必须完成以下任务:
- 读取文件
person.txt(见下文)中有关个人的信息并存储到数组p。首先将每个人的配偶指针设置为NULL值。 - 对
Mary和Tom执行合并操作。您可以通过设置他们的配偶指针指向对方(彼此的存储地址)来结婚两个人。 - 打印出数组
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++ 中使用
name和phone的原始字符数组而不是std::string?这对我来说简直是错误的。 -
"你可以通过设置他们的配偶指针指向对方(存储彼此的地址)来结婚两个人。" 这句话是#2的关键。您已经向我们展示了模板,但您尝试了什么?
-
你尝试了什么?
标签: c++ arrays pointers struct iostream