istream将空格视为分隔符。它使用区域设置来告诉它哪些字符是空格。而区域设置则包括一个ctype facet,用于分类字符类型。这样的facet可能看起来像这样:
#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;
}
};
这是一个小测试程序来展示它的工作原理:
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;
}
结果:
This
is
some
input
from
McDonald
s
and
Burger
King.
istream_iterator<string>
使用 >>
从流中读取单独的字符串,因此如果直接使用它们,应该会得到相同的结果。你需要包括的部分是创建区域设置,并使用 imbue
使流使用该区域设置。