Topic: extractors, setw() manipulator and width()
Author: Michiel Salters <salters@lucent.com>
Date: 2000/03/24 Raw View
Stephen Howe wrote:
> Consider the case of reading packed dates off a text file. With C, I can
> read a line using fgets() and then extract
> >>>>>>>>>>>>>>>>>>>>>>>
> int nConvert, iDay, iMonth, iYear;
> nConvert = sscanf("17112001", "%2d%2d%4d", &iDay, &iMonth, &iYear);
> >>>>>>>>>>>>>>>>>>>>>>>
> How is same easily achieved using ISO C++'s streams? I could extract into
> the largest integer type available and then using shifts, divisions and
> modulos break off day, month, year but what if the text file consists of
> nothing but numerical text? This is not safe.
> Thanks
> Stephen Howe
Write an extractor; i.e. istream& operator>>(istream&, Date d&).
It would know how the corresponding operator<< wrote the dates,
e.g it would know it had to get 8 chars, atoi() the first 2,
etc.
This would also allow for sanity checks, i.e. on 01132000 it could
throw BadDate(01,13,2000,E_MonthOutOfRange) or similar.
Michiel Salters
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]
Author: "Stephen Howe" <SPAMGUARDstephen.howe@dial.pipex.co.uk>
Date: 2000/03/22 Raw View
I would just like confirmation that in the ISO C++ standard it is the case
that
>>>>>>>>>>>>>>>>>>>>>>>
#include <iomanip>
#include <sstream>
char buffer[] = "1234 GHIJ";
int ival;
std::istringstream iss(buffer, 9);
iss >> std::setw(2) >> ival;
>>>>>>>>>>>>>>>>>>>>>>>
then ival will have the value 1234 and not 12 because the width is ignored.
If this is the case, this seems poor design particularly as with streams,
width is only applicable to next extractor, it being reset each time. What
harm would have occured if width (similar to scanf() in C) had applied to
_all_ extractors?
Consider the case of reading packed dates off a text file. With C, I can
read a line using fgets() and then extract
>>>>>>>>>>>>>>>>>>>>>>>
int nConvert, iDay, iMonth, iYear;
nConvert = sscanf("17112001", "%2d%2d%4d", &iDay, &iMonth, &iYear);
>>>>>>>>>>>>>>>>>>>>>>>
How is same easily achieved using ISO C++'s streams? I could extract into
the largest integer type available and then using shifts, divisions and
modulos break off day, month, year but what if the text file consists of
nothing but numerical text? This is not safe.
Thanks
Stephen Howe
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]