lineFileUtilities.h 1.9 KB
Newer Older
1
2
3
4
5
6
#ifndef LINEFILEUTILITIES_H
#define LINEFILEUTILITIES_H

#include <vector>
#include <string>
#include <algorithm>
Aaron's avatar
Aaron committed
7
#include <sstream>
Aaron's avatar
Aaron committed
8

9
10
11
using namespace std;

// split a line from a file into a vector of strings.  token = "\t"
Aaron's avatar
Aaron committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//void Tokenize(const string &str, vector<string>& tokens, const string &delimiter = "\t");
//void Tokenize(const string &str, vector<int>& tokens,    const string &delimiter = "\t");

// templated function to convert objects to strings
template <typename T>
inline
std::string ToString(const T & value) {
	std::stringstream ss;
	ss << value;
	return ss.str();
}

inline
void Tokenize(const string &str, vector<string> &tokens, const string &delimiter = "\t") {
	// Skip delimiters at beginning.
	string::size_type lastPos = str.find_first_not_of(delimiter, 0);
	// Find first "non-delimiter".
	string::size_type pos     = str.find_first_of(delimiter, lastPos);
30

Aaron's avatar
Aaron committed
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
	while (string::npos != pos || string::npos != lastPos) {
		// Found a token, add it to the vector.
		tokens.push_back(str.substr(lastPos, pos - lastPos));
		// Skip delimiters.  Note the "not_of"
		lastPos = str.find_first_not_of(delimiter, pos);
		// Find next "non-delimiter"
		pos = str.find_first_of(delimiter, lastPos);
	}
}

inline
void Tokenize(const string &str, vector<int> &tokens, const string &delimiter = "\t") {
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiter, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiter, lastPos);

    while (string::npos != pos || string::npos != lastPos) {
        // Found a token, add it to the vector.
        tokens.push_back(atoi(str.substr(lastPos, pos - lastPos).c_str()));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiter, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiter, lastPos);
    }
}
57
58

#endif /* LINEFILEUTILITIES_H */
Aaron's avatar
Aaron committed
59