我不明白你为什么真的想这样做,但是是的,这是可能的。
operator>> for std::string 读取输入字符,直到遇到空白字符。流有一个 ctype facet,用于确定字符是否为空格。
在这种情况下,您需要一个仅将\n分类为空白的ctype facet。
struct line_reader: std::ctype<char> {
line_reader(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector<std::ctype_base::mask>
rc(table_size, std::ctype_base::mask());
rc['\n'] = std::ctype_base::space;
return &rc[0];
}
};
您将包含该 ctype facet 的语言环境实例灌输给您的输入文件:
int main() {
std::vector<std::string> lines;
// Tell the stream to use our facet, so only '\n' is treated as a space.
std::cin.imbue(std::locale(std::locale(), new line_reader()));
// to keep things at least a little interesting, we'll copy lines from input
// to output if (and only if) they contain at least one space character:
std::copy_if(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, "\n"),
[](std::string const &s) {
return s.find(' ') != std::string::npos;
});
}
这里我使用了std::istream_iterator,它使用指定类型(在本例中为std::string)的提取运算符来读取数据。