How can I implement this file input format?

I want to read something from file and output it to screen.

I have a file like this:
1
2
3
4
Material: Alluminum 2.7e3
DryMaterial: Air 1.204 1.983e-5
Material: Copper 8.79e3
DryMaterial: Water 998.3 1.002e-3


I want to write code so that:
when the ifstream encounter "Material:", it will insert a material to a material vector

when it encounter "DryMaterial": it will insert a drymaterial to a drymaterial vector

So I wrote the classes like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

typedef double numeric_t;

class material_t {
public:
	string material;
	numeric_t density; //[kg/m^3]

	friend ostream & operator << (ostream & os, material_t & m);
};

ostream & operator << (ostream & os, material_t & m){
	os<<m.material<<":\tDensity:"<<m.density<<"[kg/m^3]"<<endl;

	return os;
}

class dryMaterial_t:public material_t {
public:
	numeric_t dynamicViscosity;

	friend istream & operator >> (istream & is, dryMaterial_t & m);
	friend ostream & operator << (ostream & os, const dryMaterial_t & m);
};
istream & operator >> (istream & is, dryMaterial_t & m) {
	is>>m.material>>m.density>>m.dynamicViscosity;

	return is;
}

ostream & operator << (ostream & os, const dryMaterial_t & m) {
	os<<m.material
<<":\tDensity:"<<m.density
<<"[kg/m^3]\tDynamic Viscosity:"<<m.dynamicViscosity<<"[Pa*s]"<<endl;

	return os;
}


and then I want to use it in this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main() {
	vector<material_t> M;
	vector<dryMaterial_t> DM;

	ifstream ifs("testFile");
	
	material_t m;
	dryMaterial_t dm;

    //????????????????????????????????????????????????????????????
	
    //Read in stuff   
	//if encounter Material: then ifs>>m; M.push_back(m);
	//if encouter DryMaterial: then ifs>>dm; DM.push_back(dm);
	
	//????????????????????????????????????????????????????????????
	
	ifs.close();

	for(int i=0; i<M.size(); i++) {
		cout<<M[i];
	}

	for(int i=0; i<M.size(); i++) {
		cout<<DM[i];
	}

	return 0;
}


The comment part is what I don't know how to implement, although I asked some question about ignoring text and capture number before, I still cannot figure this out. Please help me out, thank you very much!
You can use the std::string functions to parse each line and then do a string compare against your criteria i.e. if( strcmp("Material:", str_material.c_str()) == 0) //Do stuff

Stuff could be that you populate your material class with the type and density then push it into the vector or do a vector.resize(vector.size() + 1, obj);

http://www.cplusplus.com/reference/vector/vector/resize/
Last edited on
Thanks, I figured out, using stringstream!
Topic archived. No new replies allowed.