只是个小技巧,然而我现在并不能完全理解这个实现的原理,还是很弱的。
大概是自定义locale,重新定义空白符,再将自定义locale导入istream改变istream的行为。无论是cin还是ifstream都是可以用的。注意imbue完locale之后cin的全局特性都会改变,如果想要恢复原来的istream的行为的话要imbue原来的locale.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream> using namespace std; class delimiter : public std::ctype<char> { public: delimiter( const std::string& characters ) : std::ctype<char>( creatTable( characters ), false ){ } private: std::ctype_base::mask const* creatTable( const std::string& characters ) { std::ctype_base::mask* table = new std::ctype_base::mask[ std::ctype<char>::table_size ]; std::fill_n( table, std::ctype<char>::table_size, std::ctype_base::mask( ) ); for( std::string::size_type i = 0; i < characters.size( ); ++i ) { table[ characters[ i ] ] = std::ctype_base::space; } return table; } }; int main(){ delimiter delimiters( " ,-" );//usage:add desired delimitors here std::cin.imbue( std::locale( std::locale( ), &delimiters ) );//apply customize locale /*TEST CASE ONLY int a; while (cin >> a) { cerr << a << endl; }*/ return 0; } |
istream.get()修改delimiter
直接使用get()的第三個參數就可以了,cin.get(目標串, 目標輸入最大長度,分隔符);
但是只能用一個分隔符。