结构导出特定名称的数据

Structures export data for specific name

本文关键字:数据 定名称 结构      更新时间:2023-10-16

这就是我创建的结构:

#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");

}

我不能做的是。。。例如,我在这一行中输入John的名字

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 )
    {
      ...
    }
}
Students array;

你只培养了一个单身学生。你必须制作一个数组,静态的,用new、vector或其他东西赋值的。现在将其更改为

Students array[10];

并输入:

cin >> array[i].first_name;