结构导出特定名称的数据

时间:2016-01-02 14:59:03

标签: c++ arrays data-structures

这就是我创建的结构:

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

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

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

2 个答案:

答案 0 :(得分:2)

您需要一个存储所有学生的容器:我建议使用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 )
    {
      ...
    }
}

答案 1 :(得分:0)

Students array;

你只做了一个单身的学生。 你必须创建一个静态的数组,使用new,vector或sth else。 现在改为

Students array[10];

并输入它:

cin >> array[i].first_name;