これは 1 つの解決策です。
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*`.
ファイルから単語のみを読み取る場合にも、同様のトリックを適用できます。次に例を示します。