Hi, 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. Any help would be much appreciated. Thanks.
+4
A:
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)
AProgrammer
2010-02-12 10:53:36
getdelim is not exactly a GNU extension: I just found it as an Open Group Specification at http://www.opengroup.org/onlinepubs/9699919799/functions/getline.html
mkluwe
2010-02-12 11:05:32
thanks for that info..ya i know that getdelim is not a standard C function, but it works on FILE* only.
assassin
2010-02-12 11:11:16
One more question... how do I check for end-of-file using the getline function? Coz, using .eof() is not recommended as it wont signal eof until I attempt to read beyond eof.
assassin
2010-02-12 11:16:27
@mkluwe, I've been induced into error by the manpage on my system which says that getline and getdelim are GNU extensions. I've not looked if there are differences with the OpenGroup spec.
AProgrammer
2010-02-12 11:53:53
@AProgrammer: Never mind, but sometimes "is a xyz extension" has a bad connotation, and I just wanted to take that out. I know the man page, seems to be outdated…
mkluwe
2010-02-12 18:40:15
+1
A:
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"));
}
Manuel
2010-02-12 11:14:30