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

#include <vector>
#include <string>
Aaron's avatar
Aaron committed
6
#include <cstring>
7
#include <cstdlib>
Aaron's avatar
Aaron committed
8
#include <sstream>
9
#include <iostream>
Aaron's avatar
Aaron committed
10

11
12
using namespace std;

Aaron's avatar
Aaron committed
13
14
15
16
// templated function to convert objects to strings
template <typename T>
inline
std::string ToString(const T & value) {
17
18
19
    std::stringstream ss;
    ss << value;
    return ss.str();
Aaron's avatar
Aaron committed
20
21
}

Aaron's avatar
Aaron committed
22
// tokenize into a list of strings.
Aaron's avatar
Aaron committed
23
inline
24
void Tokenize(const string &str, vector<string> &elems, char delimiter = '\t') 
Aaron's avatar
Aaron committed
25
{
26
27
28
29
30
31
    // http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c/236803#236803
    // NOTE: this approach intentionally allows consecutive delimiters
    std::stringstream ss(str);
    std::string item;
    while(getline(ss, item, delimiter)) {
        elems.push_back(item);  
32
    }
Aaron's avatar
Aaron committed
33
34
}

Aaron's avatar
Aaron committed
35
// tokenize into a list of integers
Aaron's avatar
Aaron committed
36
inline
37
void Tokenize(const string &str, vector<int> &elems, char delimiter = '\t') 
Aaron's avatar
Aaron committed
38
{
39
40
41
42
43
44
45

    // http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c/236803#236803
    // NOTE: this approach intentionally allows consecutive delimiters
    std::stringstream ss(str);
    std::string item;
    while(getline(ss, item, delimiter)) {
        elems.push_back(atoi(item.c_str()));  
Aaron's avatar
Aaron committed
46
47
    }
}
48
49

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