C++讀取txt檔案,並將每一行的資訊存入結構體陣列中

a20195778發表於2020-12-11

definitions.txt檔案:
hospital 10 floor
floor 4 wing
wing 2 long_corridor
wing 1 connecting_corridor
long_corridor 21 patient_room
connecting_corridor 5 supply_room
patient_room 2 bed
patient_room 4 outlet
patient_room 1 bathroom
outlet 1 face_plate
outlet 2 socket
bathroom 1 sink
sink 2 small_rubber_washer
sink 1 large_rubber_washer
floor 1 central_lobby
central_lobby 2 couch
central_lobby 1 television

C++程式碼:

#include <string>
#include <iostream>
#include <fstream>

using namespace std;

struct node {
	string parent;
	int data;
	string child;
} p[17];

int main() {
	int  n = 0;
	ifstream in("definitions.txt", ios::in);
	if (!in.is_open()) {
		cout <<  "Error: opening file fail"  << endl;
		exit (1);
	}
	while (!in.eof() && n < 17) {
		in >> p[n]. parent >> p[n].data >> p[n].child;
		n++;
	}
//test
	for(n=0; n<17; n++) {
		cout<<p[n]. parent <<" "<<p[n].data<<" "<<p[n].child<<endl;
	}
	in.close();
	return 0;

}



作用:將txt檔案中的資訊存入結構體陣列p[17]中

相關文章