简体   繁体   中英

input values into struct array + printing out

I've been given a problem domain. Inputting into struct array C++

A class has 5 students. 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. 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.


I need to know how to input values into the struct array, and then print them out. 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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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