Re: Reading numbers from a file
In article <1149954290.927527.16870
@h76g2000cwa.googlegroups.com>, grodriguezpiriz@gmail.com
says...
Hi,
I'm reading a string of numbers from a file (using Borland C++ Builder
[ ... ]
This method seems to be working OK, but Borland CodeGuard tells me that
there's an access overrun in each sscanf call, so I guess there is a
better way of doing it. Could you please help me?
[...and elsethread mentioned wanting to ignore other data
in the file]
You've gotten a number of replies, but I thought I'd add
one more way this could be done. At least as I understand
the situation, you only want to read the numbers from the
file, and ignore everything else.
One way to handle this would be to create a locale to
reflect that for your purposes, the file contains only
numbers (digits) and other "stuff" you're going to ignore
between the digits. From a viewpoint of reading the
numbers, everything is basically the same as whitespace
-- it separates one number from another, but otherwise
has no meaning. Therefore, we start by creating a ctype
facet that says it IS whitespace:
class number_only: std::ctype<char> {
number_only() : std::ctype<char>(get_table()) {}
static std::ctype_base::mask const *get_table() {
static std::ctype_base::mask *rc;
if ( rc == 0) {
// create a character classification table
rc = new std::ctype_base::mask
[std::ctype<char>::table_size];
// say that _everything_ is whitespace
std::fill_n(rc, std::ctype,char>::table_size,
std::ctype_base::space);
// except for [0-9]:
for (int i='0'; i<='9'; i++)
rc[i] = std::ctype_base::digit;
]
return rc;
}
};
From there, we imbue the stream with a locale using that
facet, and we can just treat it as a file of numbers:
int main() {
std::ifstream x(wherever);
number_only n;
x.imbue(std::locale(std::locale(), n);
// now we can read in numbers, and everything
// else is ignored automagically.
std::vector<int> numbers;
// read in all the numbers:
std::copy(std::istream_iterator<int>(x),
std::istream_iterator<int>(),
std::back_inserter(numbers));
// just for grins, we'll display them, one per line:
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
--
Later,
Jerry.
The universe is a figment of its own imagination.