Reputation: 21169
Is there a function in c++ that works like the getdelim
function in C? I want to process a file using std::ifstream
object, so I cannot use getdelim
here.
Upvotes: 2
Views: 2071
Reputation: 52294
std::getline
, both the free function for std::string
and the member for char buffers have an overload taking a delimiter (BTW getdelim
is a GNU extension)
Upvotes: 5
Reputation: 13109
If you can use Boost then I recommend the Tokenizer library. The following example tokenizes a stream using whitespace and semicolons as separators:
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
#include<algorithm>
int main() {
typedef boost::char_separator<char> Sep;
typedef boost::tokenizer<Sep> Tokenizer;
std::string str("This :is: \n a:: test");
Tokenizer tok(str, Sep(": \n\r\t"));
std::copy(tok.begin(), tok.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
Output:
This
is
a
test
If you want to tokenize the contents of an input stream it can be done easily:
int main() {
std::ifstream ifs("myfile.txt");
typedef std::istreambuf_iterator<char> StreamIter;
StreamIter file_iter(ifs);
typedef boost::char_separator<char> Sep;
typedef boost::tokenizer<Sep, StreamIter> Tokenizer;
Tokenizer tok(file_iter, StreamIter(), Sep(": \n\r\t"));
std::copy(tok.begin(), tok.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
Upvotes: 1