gpt4 book ai didi

c++ - 特定名称的结构导出数据

转载 作者:行者123 更新时间:2023-11-30 03:45:44 25 4
gpt4 key购买 nike

这是我创建的结构:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


struct Students
{
char first_name[10];
char last_name[10];
char country[20];


};
void main()
{
Students array;
int n, i;
cin >> n;

for (i = 0; i < n; i++)
{
cout << "Name:";
cin >> array.first_name;
cout << "Last Name:";
cin >> array.last_name;
cout << "Country:";
cin >> array.country;

}

for (i = 0; i < n; i++)
{
cout << array.first_name << " ";
cout << array.last_name << " ";
cout << array.country << " ";


}
system("pause");


}

我不能做的是......例如,我输入名字约翰(在这一行)

cout << "Name:";
cin >> array.first_name;

而且我必须编写代码,一旦我输入 John(例如)显示关于他的所有信息:姓氏、国家。当我进入国家导出时:名字,姓氏。也许我没有正确解释它。因为我的英语不好。也许这就是我找不到具体信息或类似示例的原因。

Ouput example:
Name:John
Last Name: Doe
Country: England

And that's the part that i can't do:

/Info about student/
Enter Name for check:
John

and here the output must be:
Last Name: Doe
Country: England

最佳答案

您需要一个容器来存储所有学生:我建议使用 std::vector

#include <vector>

std::vector<Students> students;

将您的数据读入局部变量并将其附加到您的容器。

for (i = 0; i < n; i++)
{
Students student;
cout << "Name:";
cin >> student.first_name;
cout << "First name:";
cin >> student.last_name;
cout << "Country:";
cin >> student.country;

students.push_back( student ); // <- append student to array of students
}

遍历您的容器以打印所有学生

/* 
1. students.begin(); is a function that starts at the first value in
the array of data that you want to go through
2. students.end(); marks the end
3. the type **auto** is used, to automatically get the type for your variable,
it is more efficient since there will be no conversion and you don't have to
worry about type spelling errors
*/

for ( auto it = students.begin(); it != students.end(); it++ )
// for ( std::vector<Students>::iterator it = students.begin(); it != students.end(); it++ ) // auto <-> std::vector<Students>::iterator
{
cout << it->first_name << " ";
cout << it->last_name << " ";
cout << it->country << " ";
}

这段代码和上面的类似:

for ( size_t i = 0; i < students.size(); i++ )
{
cout << students[i].first_name << " ";
cout << students[i].last_name << " ";
cout << students[i].country << " ";
}

如果您想通过姓名查找学生,您必须使用 strcmp 来比较姓名。

for ( auto it = students.begin(); it != students.end(); it++ )
{
if ( strcmp( it->first_name, searchname ) == 0 )
{
...
}
}

关于c++ - 特定名称的结构导出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com