Reading a file using delimeters

Feb 26, 2016 at 3:35am
closed account (Sw07fSEw)
I have a project where I'm trying to save and load data from a file. I can save data to files just fine, however I have a couple questions about reading them. In my project I have a map of type map<string, vector<string>>. The key returns a vector of strings. In my project the key is a name of a holiday and the elements in the vector are different magicians available on that holiday. I'm saving my data to a file in this format:
1
2
3
Christmas	Magician_0|Magician_1|TestMagician|Andrew|Bobby|
Thanksgiving	Magician_1|TestMagician|Andrew|Bobby|
Easter	Andrew|Bobby|


The key is delimited from the vector using a tab. Then the elements of the vector are delimited from each other using pipes. The problem I'm running into is how do I know when I reach the last element of the vector? The number of elements in each vector varies and I won't know the size of it beforehand. I have the following code so far, but I'm not sure how to know when I've reached the end of the line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void loadLookupByHolidayMap() {
	ifstream lookupByHolidayFile;
	lookupByHolidayFile.open("lookupByHoliday.txt");

	while (!lookupByHolidayFile.eof()) {
		string key, magician;
		getline(lookupByHolidayFile, key, '\t'); // input data as key until a tab is found

		//pseudocode...
		while (not end of line) {
			getline(lookupByHolidayFile, magician, '|');
			myMap[key].push_back(magician); // add a magician to the vector
		}//now move onto the next line (or map key), and repeat.
	}

	lookupByHolidayFile.close();
}


If someone could point me in the right direction that'd be great.
Last edited on Feb 26, 2016 at 3:38am
Feb 26, 2016 at 4:43am
Instead of having the delimiter after the last entry leave it off:

Christmas Mag1|Mag_2|etc
Then use getline() retrieve the complete line into a std::string then use stringstream to parse that string.

Oh and by the way I recommend you stop using all those global variables.

You may also want to consider using the same delimiter for the entire line.

Last edited on Feb 26, 2016 at 4:44am
Feb 26, 2016 at 11:49am
closed account (Sw07fSEw)
Ok thank you. What do you mean by my global variables? I see only one variable in my code above that wasn't declared in the scope of the function and it's a map, myMap. Is having containers as global throughout the program considered bad practice?
Feb 26, 2016 at 1:19pm
Is having containers as global throughout the program considered bad practice?

IMO, yes.
Topic archived. No new replies allowed.