C++基礎之結構體數組

結構體數組:將自定義的結構體放入到數組中方便維護。

#include <iostream>
using namespace std;
#include<string>

/*
	定義一個結構體
*/
struct Student
{
	string name;
	int age;
	int score;
};

int main() 
{
	/*
		創建結構體數組並賦值
	*/
	struct Student stuArray[3] = 
	{
		{"小明",19,60},
		{"小紅",18,70},
		{"小軍",20,100}
	};

	/*
		修改結構體數組中的元素的值
	*/
	stuArray[2].age = 90;

	/*
		遍歷結構體數組
	*/
	int length = sizeof(stuArray) / sizeof(stuArray[0]);//數組長度:3

	for (int i = 0; i < length; i++)
	{
		cout << stuArray[i].name << stuArray[i].age << stuArray[i].score << endl;
	}
	
	system("pause");
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章