简体   繁体   English

将值输入到struct数组+打印出来

[英]input values into struct array + printing out

I've been given a problem domain. 我得到了一个问题域。 Inputting into struct array C++ 输入结构数组C ++

A class has 5 students. 一个班有5个学生。 You need to write a program to accept the following information from the user. 您需要编写一个程序来接受用户的以下信息。

First Name
Last Name
Age
Major
GPA

All these information must be obtained from the user and stored in an array. 所有这些信息必须从用户处获取并存储在数组中。 Once the array has been populated, print all these information for each and every students. 填充阵列后,为每个学生打印所有这些信息。

For doing this project, you may like to user struct, arrays, and some loops. 为了执行此项目,您可能希望使用struct,数组和一些循环。 Make sure the proper datatypes are used to store the information. 确保使用正确的数据类型来存储信息。 While accepting the GPA, you need to make sure that GPA is greater than or equal to 2 and less than or equal to 4. If the GPA of the student is beyond this range, ask the user to input the GPA again, giving him the limits. 接受GPA时,您需要确保GPA大于或等于2且小于或等于4。如果学生的GPA超出此范围,请要求用户再次输入GPA,并给他限制。


I need to know how to input values into the struct array, and then print them out. 我需要知道如何将值输入到struct数组中,然后将它们打印出来。 Here is what i have so far. 这是我到目前为止所拥有的。 Any help would be appreciated. 任何帮助,将不胜感激。

#include <iostream>
#include <string>

using namespace std;

typedef struct
{
    string firstName;
    string lastName;
    int age;
    string major;
    float GPA;
} student;


int main ()
{
    //Variable declaration
    string fnInput;
    string lnInput;
    int ageInput;
    string majorInput;
    float GPAInput;

    student students[4];

    cout << "Enter the first name:  " ;
    cin >> fnInput ;
    cout << "Enter the last name:   " ;
    cin >> lnInput ;
    cout << "Enter the age:   ";
    cin >> ageInput ;
    cout << "Enter the major:   " ;
    cin >> majorInput;
    cout << "Enter the GPA:    ";
    cin >> GPAInput ;

    cout << fnInput << lnInput << ageInput << majorInput << GPAInput ;

    /*students[0].firstName = fnInput;*/
}

To input values into the struct array, you don't need temporary variables, just store the input values directly: 要将值输入到struct数组中,不需要临时变量,只需直接存储输入值即可:

std::cout << "Enter the first name:  " ;
std::cin >> students[0].firstName;
std::cout << "Enter the age:   ";
std::cin >> students[0].age;

Output is similar: 输出类似:

std::cout << students[0].firstName;;
std::cout << students[0].age;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM