这是一种解决方案:
struct integer_only: std::ctype<char>
{
integer_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::space);
std::fill(&rc['0'], &rc['9'+1], std::ctype_base::digit);
return &rc[0];
}
};
int main() {
std::cin.imbue(std::locale(std::locale(), new integer_only()));
std::istream_iterator<int> begin(std::cin);
std::istream_iterator<int> end;
std::vector<int> vints(begin, end);
std::copy(vints.begin(), vints.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
输入:
(8,7,15)
(0,0,1) (0,3,2) (0,6,3)
(1,0,4) (1,1,5)
输出:
8 7 15 0 0 1 0 3 2 0 6 3 1 0 4 1 1 5
在线演示:http: //ideone.com/Lwx9y
在上面,您必须在std::cin
成功打开文件后替换为文件流,如:
std::ifstream file("file.txt");
file.imbue(std::locale(std::locale(), new integer_only()));
std::istream_iterator<int> begin(file);
std::istream_iterator<int> end;
std::vector<int> vints(begin, end); //container of integers!
这里,vints
是一个包含所有整数的向量。你想和他一起vints
做一些有用的事情。此外,您可以在int*
预期的地方使用它:
void f(int *integers, size_t count) {}
f(&vints[0], vints.size()); //call a function which expects `int*`.
仅从文件中读取单词时可以应用类似的技巧。这是一个例子: