dan*_*jar 1 c++ parsing stringstream
使用std::istringstream它很容易阅读由空白分隔的单词.但要解析以下行,我需要将字符/视为空格.
f 104/387/104 495/574/495 497/573/497
Run Code Online (Sandbox Code Playgroud)
如何读取由斜杠或空格分隔的值?
一种方法是定义一个分类/为空白的ctype facet :
class my_ctype : public std::ctype<char> {
public:
mask const *get_table() {
static std::vector<std::ctype<char>::mask>
table(classic_table(), classic_table()+table_size);
table['/'] = (mask)space;
return &table[0];
}
my_ctype(size_t refs=0) : std::ctype<char>(get_table(), false, refs) { }
};
Run Code Online (Sandbox Code Playgroud)
从那里,使用该ctype facet使用语言环境填充流,然后读取单词:
int main() {
std::string input("f 104/387/104 495/574/495 497/573/497");
std::istringstream s(input);
s.imbue(std::locale(std::locale(), new my_ctype));
std::copy(std::istream_iterator<std::string>(s),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1317 次 |
| 最近记录: |