2010-02-12 84 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")); 
}