[英]input values into struct array + printing out
我得到了一個問題域。 輸入結構數組C ++
一個班有5個學生。 您需要編寫一個程序來接受用戶的以下信息。
First Name
Last Name
Age
Major
GPA
所有這些信息必須從用戶處獲取並存儲在數組中。 填充陣列后,為每個學生打印所有這些信息。
為了執行此項目,您可能希望使用struct,數組和一些循環。 確保使用正確的數據類型來存儲信息。 接受GPA時,您需要確保GPA大於或等於2且小於或等於4。如果學生的GPA超出此范圍,請要求用戶再次輸入GPA,並給他限制。
我需要知道如何將值輸入到struct數組中,然后將它們打印出來。 這是我到目前為止所擁有的。 任何幫助,將不勝感激。
#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;*/
}
要將值輸入到struct數組中,不需要臨時變量,只需直接存儲輸入值即可:
std::cout << "Enter the first name: " ;
std::cin >> students[0].firstName;
std::cout << "Enter the age: ";
std::cin >> students[0].age;
輸出類似:
std::cout << students[0].firstName;;
std::cout << students[0].age;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.