欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

C++读取txt文件,并将每一行的信息存入结构体数组中

程序员文章站 2022-03-08 15:45:10
definitions.txt文件:hospital 10 floorfloor 4 wingwing 2 long_corridorwing 1 connecting_corridorlong_corridor 21 patient_roomconnecting_corridor 5 supply_roompatient_room 2 bedpatient_room 4 outletpatient_room 1 bathroomoutlet 1 face_plateoutlet 2...

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]中

本文地址:https://blog.csdn.net/a20195778/article/details/111027284