How to read from a file specific elements

Afternoon, for my c++ class I am taking, we are tasked with reading from a file of people that gives us the city, state, and zipcode of those people. The file is in the format of:


City (then a tab) State (then a tab, and the State is in the PA form) Zip Code


what we have to do is first, tell the user if the file is open, then read how many lines are in the file, and also, if there are any people from PA, NJ, MD and how many there are of those people each. Where I am stuck is telling how many people are from each state, town, and how many zip codes have hyphenes. This is what I currently have (it reads how many lines the file has basically)
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
43
44
45
46
47
48
49
50
51
52
53
 #include <iostream>
 #include <iomanip>
 #include <string>
 using namespace std ;
 #include <fstream>
 int main(void)
 {
	 const string Tab("/t") ;
	 int numLines = 0 ;
	 int numOfHyphens = 0 ;





	 cout << "Can you supply me with the file name please: " ;
	 string filename ;
	 getline(cin, filename) ;


	 ifstream fin(filename.c_str()) ;


	 if(fin.is_open())
	 {
		 cout << "File is open: " << boolalpha << fin.is_open() << endl ;
	 }
	else
	{
		cout << endl << "The file could not be opened, please check the entry and try again" << endl ;
		filename.end() ;
	}	

	


	while(!fin.eof())
	{
		string line;
		getline(fin, line);
		++numLines;
	}

	ofstream fout("Final Analysis") ;

	fout << "Number of Lines: " << numLines << endl ;





	return 0;
 }

Any help is appreciated!
Sounds like a case for std::map. It's an associative array where you can use the strings "PA", "NJ", "MD", ... as indices.

Something like counter["PA"]++; or in your case counter[state]++; where state is std::string.
I've never used it, though, but it should do the job.

The hyphen counter is straight forward by using std::string::find()
Last edited on
Topic archived. No new replies allowed.