Reading time, strings from text file and storing to vector

Basically as the title suggests. Basically, I have a text file (lyrics or subtitles, say) set out as so:

00:04:00 00:09:00 XXXXXXXXXXXXX

Where the ints are times (start and end times) and XXXXXXXX being the string.

How then would I be able to store this data into a vector?

I have a similar example where the text file uses years (ie 2000 2010 XXX) and I was able to store this in a vector and print to console without issues.

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
54
55
56
57
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "timer.h"

using namespace std;

class Lyrics{
	int _stime;
	int _etime;
	int _line;
	string _lyric;

public:
	//Construct lyrics with initial values for each field
	Lyrics(int st, int et, int l, string &lc) : _stime(st), _etime(et), _line(l), _lyric(lc){}

	//Selector functins for fields
	int stime() {return _stime;}
	int etime() {return _etime;}
	int line() {return _line;}
	const string & lyric() const {return _lyric;}

	//Is the time right for the words?
	bool rightTime(int y) const{
		return _stime <= y && y <= _etime;
	}
		

};

//Read lyrics from text file and add to vector.
void read_lyrics(vector<Lyrics> & v){
	ifstream in("pok.txt");
	int st, et, l;
	string lc;
	while(in >> st >> et >> l >> lc)
		v.push_back(Lyrics(st, et, l, lc));
}

//Print lyrics
int main(){
	//Timer timer;
	vector<Lyrics> lyrics;
	read_lyrics(lyrics);
	
		
	for(int i=0; i <= lyrics.size(); i++){
	Lyrics w = lyrics[i];
	//if (w.rightTime())
		cout << w.stime() << w.etime() << w.line() << w.lyric() << "\n";
	
	//cout << "Test.\n";
	}
return 0;
}


I also need a way that I can use time as an input so the words can show up based on the times from the text file (ie at 4 seconds line 1 is printed, at 7 seconds line 2....and so on).

Thank you for your help.
The reason you can't do it right now is because the >> operator will read up to a space (or a newline) and then stop, however in this case you want to read up to the next ':'. I would suggest using std::getline() first, then parsing the string yourself with .find() and .substr().
Thanks, I'll take a look into that.

I forgot to mention though that I get an error of "vector out of bounds". If I just gave main() a simple thing (a cout, for example) it compiles fine. So something in the for loop is giving me my error.

Also, even if the file formats has no use ':' and just ints, I still get the error.
Last edited on
for(int i=0; i <= lyrics.size(); i++){ remove the equals sign from the comparison :
for(int i=0; i < lyrics.size(); i++){
Topic archived. No new replies allowed.