是否像getdelim这样的函数是c ++?

时间:2010-02-12 10:50:06

标签: c++ c file-io

c ++中的函数是否与c中的getdelim函数一样?我想使用std :: ifstream对象处理文件,所以我不能在这里使用getdelim。 任何帮助将非常感激。 感谢。

2 个答案:

答案 0 :(得分:4)

getline,std :: string的自由函数和char缓冲区的成员都有一个带分隔符的重载(BTW getdelim是一个GNU扩展)

答案 1 :(得分:1)

如果您可以使用Boost,那么我推荐使用Tokenizer库。以下示例使用空格和分号作为分隔符来标记流:

#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"));
}

输出:

This
is
a
test

如果要标记输入流的内容,可以轻松完成:

 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"));
 }