结构是一种由程序员自己定义的、由其他变量类型组合而成的数据类型。其所能包含的变量的个数是没有限制的。
实例1:简单数据库读写
1 #include <iostream>
2 #include <fstream> //文件操作
3 #include <windows.h> // 为了使用Sleep()函数
4
5 struct FishOil
6 {
7 std::string name;
8 std::string uid;
9 char sex;
10 };
11
12 bool InitFishC();
13 bool ReadFishC();
14 void RecordFishC();
15 bool WriteFishC(FishOil *OilData);
16
17 int main()
18 {
19 int i;
20
21 InitFishC(); // 初始化数据。
22 while( 1 )
23 {
24 std::cout << "请选择需要进行的操作: \n";
25 std::cout << "1. 打印数据到屏幕\n";
26 std::cout << "2. 录入数据\n";
27 std::cout << "3. 退出程序\n";
28 std::cin >> i;
29
30 switch( i )
31 {
32 case 1:
33 if( ReadFishC() )
34 std::cout << "成功读取文件^_^\n\n";
35 else
36 std::cout << "读取文件失败T_T\n\n";
37 break;
38 case 2:
39 RecordFishC();
40 break;
41 case 3:
42 return 0;
43 }
44 }
45
46 return 0;
47
48 }
49
50 bool InitFishC()
51 {
52 FishOil OilInit = {"小甲鱼", "fishc00001", 'M'};
53
54 if( WriteFishC(&OilInit) == false )
55 std::cout << "初始化失败T_T\n";
56 }
57
58 bool ReadFishC() //读文件
59 {
60 std::string temp;
61 std::ifstream fileInput("FishC.txt");
62
63 if( fileInput.is_open() )
64 {
65 std::cout << "\n正在输出记录数据...... ";
66 for( int i=0; i <= 100; i++ ) // 打印百分比
67 {
68 std::cout.width(3);
69 std::cout << i << "%";
70 Sleep(50);
71 std::cout << "\b\b\b\b";
72 }
73 std::cout << "\n\n";
74
75
76 std::cout << " 姓名 " << " 身份证 " << " 性别 " << "\n\n";
77
78 while( std::getline( fileInput, temp ) )
79 {
80 std::cout << temp << " ";
81 std::cout << "\n";
82 }
83 std::cout << "\n\n";
84
85 return true;
86 }
87 else
88 return false;
89 }
90
91 void RecordFishC()//录入数据
92 {
93 char goon, Save;
94 FishOil OilData;
95 FishOil *pOilData;
96
97 goon = 'Y';
98 while( 'Y' == goon )
99 {
100 std::cout << "请输入鱼C账号: ";
101 std::cin >> OilData.name;
102 std::cout << "请输入鱼C身份证:";
103 std::cin >> OilData.uid;
104 std::cout << "请输入性别:";
105 std::cin >> OilData.sex;
106
107 std::cout << "录入成功, 请问需要保存吗?(Y/N)";
108 std::cin >> Save;
109 if( 'Y' == Save )
110 {
111 pOilData = &OilData;
112 if( WriteFishC( pOilData ) )
113 std::cout << "成功写入文件^_^\n";
114 else
115 std::cout << "写入文件失败T_T\n";
116 }
117 else
118 {
119 return;
120 }
121
122 std::cout << "/n请问需要再次录入吗?(Y/N)";
123 std::cin >> goon;
124 }
125 }
126
127 bool WriteFishC( FishOil *pOilData )//写文件
128 {
129 std::ofstream fileOutput("FishC.txt", std::ios::app);
130 // std::ios::app用来说明在老数据追加新数据
131 if( fileOutput.is_open() )
132 {
133 fileOutput << pOilData->name << " ";
134 fileOutput << pOilData->uid << " ";
135 fileOutput << pOilData->sex << "\n";
136
137 fileOutput.close();
138 std::cout << "数据成功保存到FishC.txt\n\n";
139 return true;
140 }
141 else
142 std::cout << "保存失败T_T\n";
143 return false;
144 }