在使用std :: fstream读取文本文件时,如何使用非默认分隔符?

Fro*_*and 17 c++ fstream ifstream

在我的C++代码中,我想从文本文件(*.txt)中读取并标记每个条目.更具体地说,我希望能够从文件中读取单个单词,例如"格式","堆栈","杰森","欧洲" .

我选择用来fstream执行这个任务,我不知道如何设置它的分隔符给我想要使用的(空格,\n以及连字符,甚至是"麦当劳"中的撇号).我想空间并且\n是默认分隔符,但连字符不是,但我想把它们当作分隔符,这样在解析文件时,我会把"blah blah xxx animal - cat"中的单词简单地称为"blah"," blah","xxx","animal","cat".

也就是说,我希望能够从"堆栈溢出","你是" 获得两个字符串,并且仍然能够同时维护\n和空格作为分隔符.

Jer*_*fin 20

一个istream将"白色空间"视为分隔符.它使用区域设置来告诉它哪些字符是空白区域.反过来,语言环境包括一个facet对字符类型进行分类的ctype .这样的方面可能看起来像这样:

#include <locale>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <sstream>

class my_ctype : public
std::ctype<char>
{
    mask my_table[table_size];
public:
    my_ctype(size_t refs = 0)  
        : std::ctype<char>(&my_table[0], false, refs)
    {
        std::copy_n(classic_table(), table_size, my_table);
        my_table['-'] = (mask)space;
        my_table['\''] = (mask)space;
    }
};
Run Code Online (Sandbox Code Playgroud)

一个小测试程序,以显示它的工作原理:

int main() {
    std::istringstream input("This is some input from McDonald's and Burger-King.");
    std::locale x(std::locale::classic(), new my_ctype);
    input.imbue(x);

    std::copy(std::istream_iterator<std::string>(input),
        std::istream_iterator<std::string>(),
        std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

This
is
some
input
from
McDonald
s
and
Burger
King.
Run Code Online (Sandbox Code Playgroud)

istream_iterator<string>用于>>从流中读取单个字符串,因此如果直接使用它们,您应该得到相同的结果.您需要包含的部分是创建语言环境并使用它imbue来使流使用该语言环境.