2010-02-12 80 views
0

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

回答

4

函数getline,既为的std :: string免费的功能和字符缓冲区的成员有过载采取了分隔符(BTW getdelim是GNU扩展)

+0

getdelim不完全是一个GNU扩展:我刚刚在http://www.opengroup.org/onlinepubs/9699919799/functions/getline.html – mkluwe 2010-02-12 11:05:32

+0

上发现它是一个开放组规范,感谢info..ya我知道getdelim不是一个标准的C函数,但它只适用于FILE *。 – assassin 2010-02-12 11:11:16

+0

还有一个问题......我如何使用getline函数检查文件结束? Coz,不推荐使用.eof(),因为它不会提示eof,直到我尝试读取超出eof。 – assassin 2010-02-12 11:16:27

1

如果你可以使用升压那么我建议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")); 
}